如何在 MS SQL 中将分组记录合并为一行

How to merge grouped records into one row in MS SQL

如何将分组记录 (byt SurvId) 合并到一行中,其中列 Mode 是列名称的一部分?

这个

ID  SurvId   Mode            A       B  
---------------------------------------
1   1        Unrestricted    1       3
2   1        Restricted      5       2 
3   2        Unrestricted    6       4
4   2        Restricted      4       1 

进入这个

SurvId   UnrestictedA   UnrestrictedB   RestrictedA   RestrictedB
------------------------------------------------------------
1        1              3               5             2
2        6              4               4             1

您可以使用条件聚合:

select survid,
       max(case when mode = 'Unrestricted' then A end) as unrestricted_a,
       max(case when mode = 'Restricted' then A end) as restricted_a,
       max(case when mode = 'Unrestricted' then B end) as unrestricted_b,
       max(case when mode = 'Restricted' then B end) as restricted_b
from t
group by survid;