Transact SQL:具有特定逻辑的有序行内的字符串连接

Transact SQL: String concatenation within ordered rows with certain logic

鉴于 table

CREATE TABLE dbo.T
(
    CN char(2) NOT NULL,
    GN int NOT NULL,
    SG int NOT NULL,
    SN int NOT NULL,
    C varchar(3),
    CB varchar(max)
);
INSERT INTO dbo.T(CN,GN,SG,SN,C,CB)
VALUES
('P1',9,6,0,'020','AAA'),
('P1',9,6,1,NULL,'BBB'),
('P1',9,6,2,'020','CCC'),
('P1',9,6,3,NULL,'DDD'),
('P1',9,6,4,'020','EEE'),
('P1',9,6,5,NULL,'FFF'),
('P1',9,6,6,'020','GGG'),
('P1',9,6,7,NULL,'HHH'),
('P1',9,6,8,'020','JJJ'),
('P1',9,6,9,NULL,'LLL'),
('P1',9,6,10,NULL,'MMM'),
('P1',9,6,11,NULL,'NNN')

所需的输出是这样的:

CN  GN  SG  SN  C    CB
P1  9   6   0   020  AAABBB
P1  9   6   2   020  CCCDDD
P1  9   6   4   020  EEEFFF
P1  9   6   6   020  GGGHHH
P1  9   6   8   020  JJJLLLMMMNNN

因此您遍历了按 CNGNSGSN 排序的所有行。从 C 中第一次出现的非 NULL 值开始。当下一行在 C 列中获得 NULL 值时,只要下一行在 C.

列中不为 NULL,则连接 CB

我会使用 CTE 累积 聚合:

with t as (
     select t.*, 
            sum(case when c is not null then 1 else 0 end) over (partition by cn, gn, sg order by sn) as grp
     from dbo.T as t  
)
select distinct t.CN, t.GN, t.SG, t.SN, t.C, tt.cb
from t cross apply
     ( select ''+t1.cb
       from t t1 
       where t1.cn = t.cn and t1.gn = t.gn and t1.sg = t.sg and t1.grp = t.grp
       for xml path('')
     ) tt(cb)
where t.C is not null;