Skip to content
Advertisement

Oracle SQL query times in one line

I apologize in advance for any formatting issues.

Here is some sample data.

enter image description here

Here is what I would like to produce:

enter image description here

Here is what I get when I use a series of case when statements

enter image description here

Any coding help is much appreciated.

Advertisement

Answer

That is what the PIVOT clause was created for:

-- sample data:
with t(id, quarter, sales) as (
   select 1,1,13 from dual union all
   select 1,2,14 from dual union all
   select 1,3,21 from dual union all
   select 1,4,17 from dual union all
   select 2,1,11 from dual union all
   select 2,2,23 from dual union all
   select 2,3,18 from dual union all
   select 2,4,19 from dual 
)
-- query:
select *
from t
pivot(
  sum(sales) 
  for Quarter in (
        1 as Q1
       ,2 as Q2
       ,3 as Q3
       ,4 as Q4)
);

        ID         Q1         Q2         Q3         Q4
---------- ---------- ---------- ---------- ----------
         1         13         14         21         17
         2         11         23         18         19
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement