不同的行值为列Sql Server

时间:2013-07-04 12:36:10

标签: sql-server-2005

我有一个带有3列的临时表,如下所示,

    JobID JobType        JobValue
    12    HR              Jesica
    23    MANAGER         Ravi
    5     MANAGER         Jacob
    60    EMPLOYEE      Kiruan
    45    MANAGER         Abidam
    27    HR              Kamsura
    21    MANAGER         Chio Bin
    87    EMPLOYEE      Gamanya
    22    HR              Pradeep
    56    HR              Hari
    67    EMPLOYEE      Om
    14    MANAGER         Kiran




My result table should be like 


    JobID  HR   MANAGER  EMPLOYEE   
    12      
    23      
    5       
    60          
    45      
    27          
    21      
    87          
    22          
    56      
    67          
    14      

Jobvalue列值应该进入结果集。

我试过如下。

使用distict Jobtype行值创建临时表。 然后将while循环插入的JobValue列值用于该表。

但它看起来很脏。

任何人都可以给我一个很好的建议来完成这个。

谢谢,

2 个答案:

答案 0 :(得分:3)

您应该可以使用PIVOT函数来获得结果:

select jobid, hr, manager, employee
from yourtable
pivot
(
  max(jobvalue)
  for jobtype in (hr, manager, employee)
) piv;

请参阅SQL Fiddle with Demo

如果您想在不显示jobid的情况下列出每个jobvalue下的jobType,那么您可以使用:

select hr, manager, employee
from
(
  select jobtype, jobvalue,
    row_number() over(partition by jobtype order by jobid) rn
  from yourtable
) d
pivot
(
  max(jobvalue)
  for jobtype in (hr, manager, employee)
) piv;

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

试试这个

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(jobtype) 
                    from yourtable
                    group by jobtype
                    ORDER BY jobtype
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
--SELECT @cols
set @query = 'SELECT  JobID,' + @cols + ' from 
             (
                select JobID, jobtype, jobvalue from yourtable
            ) x
            pivot 
            (
                MAX(jobvalue)
                for jobtype in (' + @cols + ')
            ) p '

execute(@query)