以行值作为列名和组连接的分组依据

Group By with row values as column name and group concat

我正在寻找 SQL 问题的解决方案:

我这样输入 table:

RId AId Type
76 734 TKI
76 528 NPlat
76 735 TKI
77 713 Plat
77 749 IO
77 739 TKI
77 714 NPlat
78 518 Plat
73 519 Plat
73 518 Plat

我想要这样的输出:

RId TKI IO NPlat Plat
73 518, 519
76 734, 735 528
77 739 749 714 713
78 518

我试过 PIVOT,但它不起作用。还尝试将 GROUP BYPARTITION BY 一起使用,但没有成功。

任何人都可以解决这个问题吗?

注意:我使用的是 Microsoft SQL Server 2016 (SP3)。

已编辑: 我的尝试:

select 
RId,
case when Type = 'TKI' then STRING_AGG(AId, ' ') END AS TKI,
case when Type = 'IO' then STRING_AGG(AId, ' ') END AS IO,
case when Type = 'NPlat' then STRING_AGG(AId, ' ') END AS NPlat,
case when Type = 'Plat' then STRING_AGG(AId, ' ') END AS Plat
from tbl_A
group by RId, Type;

STRING_AGG 不是 SQL 服务器 2016 中的通用函数。

select 
RId,
[TKI] = COUNT(*) over(partition by Type),
[IO] = COUNT(*) over(partition by Type),
[NPlat] = COUNT(*) over(partition by Type),
[Plat] = COUNT(*) over(partition by Type)
from tbl_A
group by RId, Type
order by RId;

您可以先将Aid拼接成csv格式,然后进行主元

select *
from   (
           select  Rid, [Type], 
                   Aid = stuff(
                             (select ',' + convert(varchar(10), x.Aid)
                             from   tbl x 
                             where  x.Rid = t.Rid
                             and    x.[Type] = t.[Type]
                             order by x.Aid
                             for xml path('')), 1, 1, '')
           from    tbl t
           group by Rid, [Type]
       ) d
       pivot
       (
            max(Aid)
            for [Type] in ([TKI], [IO], [NPlat], [Plat])
       ) p 

dbfiddle demo

带 Pivot 的简单使用:

SELECT RID,[TKI],[IO],[NPlat],[Plat]
FROM 
(SELECT RID,TYPE,AID = STUFF((
                                SELECT ',' + CONVERT(VARCHAR,AID)
                                FROM test t
                                WHERE t.RID = test.RID AND t.TYPE = test.type                               
                                FOR XML PATH('')
                                ), 1, 1, '')
FROM test 
)sorce
PIVOT 
( 
max(AID) FOR type IN ([TKI],[IO],[NPlat],[Plat]) 
) AS PivotTable