Distinct Row values as Columns Sql Server

2019-07-02 00:23发布

I have a temp table with 3 Columns Like below,

    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 column values should come into result set.

I have tried like below.

Created a temp table with distict Jobtype row values. then using while loop inseted JobValue column values into that table.

But it looks very dirty procedure.

Can any one give me a good suggesion to complete this.

Thanks,

2条回答
我只想做你的唯一
2楼-- · 2019-07-02 00:44

You should be able to use the PIVOT function to get the result:

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

See SQL Fiddle with Demo.

If you want to list the jobvalue under each jobType without showing the jobid, then you could use:

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;

See SQL Fiddle with Demo

查看更多
一纸荒年 Trace。
3楼-- · 2019-07-02 01:04

Try this

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)
查看更多
登录 后发表回答