Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct Row values as Columns Sql Server

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,

like image 663
BhargavaKatta Avatar asked May 12 '26 14:05

BhargavaKatta


1 Answers

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

like image 170
Taryn Avatar answered May 16 '26 11:05

Taryn