Oracle How to turn rows to columns
Consider this query:
select job_id, count(*)
from employees
where job_id in ('AD_PRES', 'AD_VP', 'IT_PROG')
group by job_id
It returns this result set:
JOB_ID COUNT(*)
---------- ----------------------
AD_PRES 1
AD_VP 2
IT_PROG 5
3 rows selected
Now, you want to transpose the result set and turn the JOB_ID values into columns in a single row. Here is one way of doing it:
select sum(case when job_id='AD_PRES' then 1 else 0 end) as AD_PRES,
sum(case when job_id='AD_VP' then 1 else 0 end) as AD_VP,
sum(case when job_id='IT_PROG' then 1 else 0 end) as IT_PTOG
from (
select job_id
from employees
where job_id in ('AD_PRES', 'AD_VP', 'IT_PROG'))
The result:
AD_PRES AD_VP IT_PTOG
---------------------- ---------------------- ----------------------
1 2 5
1 rows selected
Comments