2013-08-16 56 views
0

我有这样的数据:从行创建列名称?

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

数据应该是这样的:

1   2   3   4 
New york Washington denmark Holand 
+0

是否张贴问题之前,没有人搜索? – SQLMason

回答

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

或者你可以使用旋转功能:

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

SQL Fiddle with Demo

+0

这是我唯一能说的优秀。没有词。完善 – user2690007