从行创建列名?

时间:2013-08-16 16:02:50

标签: sql-server pivot

我有这些数据:

name      | coulmnnuber
Newyork   | 1
washington| 2
denmark   | 3
Holand    | 4

数据应如下所示:

1           2           3          4
New york    Washington  denmark    Holand

1 个答案:

答案 0 :(得分:4)

您可以使用带有CASE表达式的聚合函数将数据行转换为列:

select 
  max(case when coulmnnuber = 1 then name end) [1],
  max(case when coulmnnuber = 2 then name end) [2],
  max(case when coulmnnuber = 3 then name end) [3],
  max(case when coulmnnuber = 4 then name end) [4]            
from yourtable;

请参阅SQL Fiddle with Demo

或者您可以使用PIVOT功能:

select [1], [2], [3], [4]
from yourtable
pivot
(
  max(name)
  for coulmnnuber in ([1], [2], [3], [4])
) piv;

请参阅SQL Fiddle with Demo

相关问题