2013-07-11 51 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