Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Masalah dalam menghitung nol dan kemudian menggabungkannya dengan baris yang ada

Agak berantakan dan kemungkinan besar bisa diperbaiki

;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



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara Memasukkan Nilai ke dalam Kolom IDENTITAS di SQL Server

  2. Secara otomatis menyelesaikan konflik penggabungan kunci utama

  3. Menyebarkan proyek database SQL Server (SSDT) ​​melalui baris perintah

  4. Menyiapkan dan Mengonfigurasi Grup Ketersediaan Selalu Aktif di SQL Server

  5. Perbaiki "Kesalahan overflow aritmatika mengonversi IDENTITAS ke tipe data ..." di SQL Server