2013-07-11 53 views
0

我列看起来像这样的:列行维护用户ID

UserID col1 col2 col3 col4 
--------------------------------------- 
233432 45.2 34.2 ''  0.52 

我希望它看起来像这样:

UserID colID value 
------------------------- 
233432 col1  45.2 
233432 col2  34.2 
233432 col3  '' 
233432 col4  0.52 

我发现下面这个链接:

column to row in sql server?

但它并没有真正回答我have.my问题的问题。我使用SQL Server 2012

回答

1
Select UserID,'col1',col1 as 'value' from mytable 
union 
Select UserID,'col2',col2 from mytable 
union 
Select UserID,'col3',col3 from mytable 
union 
Select UserID,'col4',col4 from mytable 
2

由于您使用的SQL Server 2008+,你可以使用CROSS APPLY与值unpivot的数据:

select t.userid, 
    c.colid, 
    c.value 
from yourtable t 
cross apply 
(
    values 
    ('col1', col1), 
    ('col2', col2), 
    ('col3', col3), 
    ('col4', col4) 
) c (colid, value); 

SQL Fiddle with Demo