多行成列,列值按SQL Server中的列分组

时间:2019-05-12 20:37:10

标签: sql sql-server

如何通过以下方式将行转换为列组:

enter image description here

所需的结果将是这样的:

enter image description here

1 个答案:

答案 0 :(得分:2)

如果您有指定顺序的列,则可以使用条件聚合:

select max(case when columnname = 'SupplierGSTin' then value end) as SupplierGSTin,
       max(case when columnname = 'DocumentNumber' then value end) as DocumentNumber,
       max(case when columnname = 'SupplyType' then value end) as SupplyType
from (select t.*,
             row_number() over (partition by columnname order by ?) as seqnum
      from t
     ) t
group by rownum;

?用于指定顺序的列。