如何将表列转换为行

时间:2016-12-24 00:00:08

标签: sql-server linq

我有一张如下表:

+-----------+------------+--------+
|   Col1    |    Col2    |  Col3  |
+-----------+------------+--------+
|  12345678 | FirstName  | John   |
|  12345678 | LastName   | Smith  |
| 987456321 | LastName   | Clancy |
| 987456321 | MiddleName | T      |
| 987456321 | Height     | 176cm  |
| 654125878 | FirstName  | Tan    |
| 654125878 | Weight     | 150lb  |
+-----------+------------+--------+

如何将其转换为:

+-----------+-----------+------------+----------+--------+--------+
|    ID     | FirstName | MiddleName | LastName | Height | Weight |
+-----------+-----------+------------+----------+--------+--------+
|  12345678 | John      | null       | Smith    | null   | null   |
| 987456321 | null      | T          | Clancy   | 176cm  | null   |
| 654125878 | Tan       | null       | null     | null   | 150lb  |
+-----------+-----------+------------+----------+--------+--------+

1 个答案:

答案 0 :(得分:3)

我认为条件聚合可以解决这个问题。

假设您不需要动态

Select ID = Col1
      ,FirstName   = max(case when Col2='FirstName'   then Col3 else null end)
      ,MiddleName  = max(case when Col2='MiddleName ' then Col3 else null end)
      ,LastName    = max(case when Col2='LastName '   then Col3 else null end)
      ,Height      = max(case when Col2='Height'      then Col3 else null end) 
      ,Weight      = max(case when Col2='Weight'      then Col3 else null end) 
 From YourTable
 Group By Col1

如果你需要动态

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([Col2]) From Yourtable  Order by 1 For XML Path('')),1,1,'') 
Select  @SQL = '
Select [Col1] as ID ,' + @SQL + '
From   YourTable
 Pivot (max(Col3) For [Col2] in (' + @SQL + ') ) p'
Exec(@SQL);

如果有帮助,动态数据透视表生成的SQL如下:

Select [Col1] as ID ,[FirstName],[Height],[LastName],[MiddleName],[Weight]
From   YourTable
Pivot  (max(Col3) For [Col2] in ([FirstName],[Height],[LastName],[MiddleName],[Weight]) ) p