如何将行转换为列 Sql 服务器

How to transform Rows into Column Sql Server

如何为 SQL serer

中的以下 table 数据将行转换为列

Actual table

LabelID  |  LabelName
---------------------
    1    |  Label1
    2    |  Label2
    3    |  Label3
    4    |  Label4
    5    |  Label5

Expected table

    1  |    2   |   3   |   4    |  5   
------------------------------------------
Label1 | Label2 | Labe3 | Label4 | Label15

这是一个示例查询,可以帮助您获得所需的输出。如果您实际上也有 5 行,则此查询将起作用。如果行数较多且数据种类繁多,您需要根据您的数据和所需的输出调整查询。

SELECT 
MAX(CASE WHEN LabelID = 1 THEN  LabelName END) [1],
MAX(CASE WHEN LabelID = 2 THEN  LabelName END) [2],
MAX(CASE WHEN LabelID = 3 THEN  LabelName END) [3],
MAX(CASE WHEN LabelID = 4 THEN  LabelName END) [4],
MAX(CASE WHEN LabelID = 5 THEN  LabelName END)[5]
FROM your_table