Oracle SQL раз запроса в одной строке - PullRequest
0 голосов
/ 14 июля 2020

Заранее прошу прощения за любые проблемы с форматированием.

Вот несколько примеров данных.

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

введите описание изображения здесь

Любая помощь по кодированию приветствуется.

Ответы [ 2 ]

1 голос
/ 14 июля 2020

Вам нужна агрегация:

select id,
       sum(case when quarter = 1 then sales end) as q1_sales,
       sum(case when quarter = 2 then sales end) as q2_sales,
       sum(case when quarter = 3 then sales end) as q3_sales,
       sum(case when quarter = 4 then sales end) as q4_sales
from t
group by id;
0 голосов
/ 15 июля 2020

Вот для чего было создано предложение PIVOT:

-- 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...