Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Problema em contar nulos e depois mesclá-los com as linhas existentes


Meio confuso e provavelmente pode ser melhorado
;With RawData AS
(
    select * from @t
)
,Ranked1 as
(
    select *, RANK() OVER (PARTITION BY GroupId, RowID ORDER BY ID, GroupId, RowID) R from @t
)
,Ranked2 as
(
    select *, R - RANK() OVER (PARTITION BY GroupId, RowID ORDER BY ID, GroupId, RowID) R2 from Ranked1
    where Data is null
)
,Ranked3 as
(
    select MIN(ID) as MinID, GroupId, RowID, R2, COUNT(*) C2 from Ranked2
    group by GroupId, RowID, R2
)
,Ranked4 as
(
    select RD.ID, RD.GroupId, RD.RowID, ISNULL(Data, C2) as C3 from RawData RD
    left join Ranked3 R3 on RD.ID = R3.MinID and RD.GroupId = R3.GroupId and RD.RowID = R3.RowID
    where ISNULL(Data, C2) is not null
)
,Grouped as
(
    select GroupId, RowID,
        (
            select isnull(C3, '') from Ranked4 as R41
            where R41.GroupId = R42.GroupId and R41.RowID = R42.RowID
            order by GroupId, RowID for xml path('')
        ) as C4
    from Ranked4 as R42
    group by GroupId, RowID
)
    select GroupId,
        stuff((
            select ',' + C4 from Grouped as G1
            where G1.GroupId = G2.GroupId
            order by GroupId for xml path('')
        ), 1, 1, '')
    from Grouped G2
    group by GroupId