Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

SQL Server combina più righe in una

Penso che la chiave per questo sia capire in quali blocchi cadono i 188,198 e 88. Nel cte sotto sto lavorando sulla base che un 88 termina sempre un blocco e sto assegnando il rowid dell'88 a tutti i rowid meno di esso, abilitando così il gruppo.

declare @t table(client_id int, m_id int,chid int,inv_id int,input varchar(20),dt datetime,rowid int)
insert into @t values
(133,928,9581,188,'yes_b1','2016-08-16 01:00:00:000',1),
(133,929,9581,198,'yes_b1','2016-08-16 01:10:00:000',2),
(133,930,9581,82,'referred_b1','2016-08-16 01:30:00:000',3),
(133,935,9584,188,'yes_b2','2016-08-16 01:00:00:000',5),
(133,936,9584,198,'yes_b2','2016-08-16 01:00:00:000',6),
(133,937,9584,82,'referred_b2','2016-08-16 01:00:00:000',7)

;with cte as
(
select s.*,
        lag(s.hi,1,0) over (order by s.inv_id) as lo 
from
(
select  inv_id,rowid as hi
from @t
where inv_id = 82
)s
)
select t.client_id,
        max(case when t.inv_id = 188 then input end) 'input(188)',
        max(case when t.inv_id = 198 then input end) 'input(198)',
        max(case when t.inv_id = 82  then input end) 'input(82)',
        max(case when t.inv_id = 188 then dt end) 'date(188)',
        max(case when t.inv_id = 198 then dt end) 'date(198)',
        max(case when t.inv_id = 82  then dt end) 'date(82)' 
from @t t
join cte on rowid <= cte.hi and rowid > cte.lo
group by client_id,cte.hi

Risultato

client_id   input(188)           input(198)           input(82)            date(188)               date(198)               date(82)
----------- -------------------- -------------------- -------------------- ----------------------- ----------------------- -----------------------
        133 yes_b1               yes_b1               referred_b1          2016-08-16 01:00:00.000 2016-08-16 01:10:00.000 2016-08-16 01:30:00.000
        133 yes_b2               yes_b2               referred_b2          2016-08-16 01:00:00.000 2016-08-16 01:00:00.000 2016-08-16 01:00:00.000