MS SQL 2017
CREATE TABLE TEST(parts nvarchar(10),flag nvarchar(10),groupno nvarchar(10));
insert into TEST
values ('p1','m','01'),
('p2','r','01'),
('p3','m','02'),
('p4','r','02'),
('p5','r','02'),
('p6','m','03');
select TEST.*,M.partsnew
from TEST
--
left join (
select groupno,
partsnew=string_agg(parts,',')
from TEST
where 1=1
and flag='r'
group by groupno
) as M on M.groupno=TEST.groupno
--
where 1=1
and flag='m'
order by parts
使用 SQL Server 2017 的 STRING_AGG 功能
DROP TABLE IF EXISTS Demo
CREATE TABLE Demo(parts nvarchar(10),flag nvarchar(10),groupno nvarchar(10));
INSERT INTO Demo (parts,flag,groupno) values
('p1','m','01'),
('p2','r','01'),
('p3','m','02'),
('p4','r','02'),
('p5','r','02'),
('p6','m','03');
SELECT
groupno ,
MAX(IIF(flag = 'm' , Parts , null)) AS [Master] ,
STRING_AGG(IIF(flag = 'r' , Parts , null) , ',') AS DetailList
FROM Demo
GROUP BY groupno