将行转换为列和列到SQL Server

时间:2016-07-15 14:45:17

标签: sql sql-server sql-server-2008

这是我现有的表格:

id  |user-LastName  |user-FirstName |manager-lasename   |manager-firstname
22   Gould              Todd             raj                 kumar
23   Volk               Michael          anil                tej
24   Sarosiek           Kristi           mahesh              banda

我需要得到以下结果:

id  name                user          manager      
22  last name           gould          raj     
22  first name          todd           kumar       
23  last name           Volk           anil    
23  first name          Michael        tej     
24  last name           Sarosiek       mahesh      
24  first name          Kristi         banda    

我尝试过使用PIVOT,但我无法让它发挥作用。有没有人有解决方案?

2 个答案:

答案 0 :(得分:1)

尽管我认为这里的设计是你问题的症结所在,你可以用UNION轻松获取数据。

select id
    , 'LastName' as name
    , userLastName
    , ManagerLastName
from SomeTable

union all

select id
    , 'FirstName' as name
    , userFirstName
    , ManagerfirstName
from SomeTable

order by id
    , name desc

答案 1 :(得分:0)

嗨,你真的没有尝试过这里的Pivot,而只是以不同的方式定位你现有的数据。

获得所需结果的一种方法是创建两个查询和联合:

select id, 'FirstName' as name, user_firstName as "user" , manager_firstname as manager from p
union
select id, 'LastName' as name, user_LastName as "user" , manager_lastname as manager from p;

Here is a functional example