Разделить столбец на несколько столбцов по критериям - PullRequest
0 голосов
/ 31 января 2020

У меня есть запрос, подобный следующему:

select
  table.date,
  table.shift,
  sum(table.value)
from
  db.table
where
  table.date >= date '2020-01-01' and
  table.filter = 'type'
group by
  table.date,
  table.shift
order by
  table.date,
  table.shift;

, который возвращает данные таким образом:

date       | shift | sum(value)
-----------|-------|------------
2020-01-06 | 1     | 15
2020-01-06 | 3     | 12
2020-01-07 | 1     | 20
2020-01-07 | 2     | 38
2020-01-09 | 1     |  6
2020-01-09 | 2     | 22
2020-01-09 | 3     | 14
2020-01-10 | 1     | 17
2020-01-10 | 2     |  3
2020-01-10 | 3     | 10

Я пытаюсь получить это так, но я не знаю как:

date       | 1  | 2  | 3
-----------|----|----|----
2020-01-06 | 15 |    | 12
2020-01-07 | 20 | 38 |
2020-01-09 |  6 | 22 | 14
2020-01-10 | 17 |  3 | 10

Ответы [ 4 ]

1 голос
/ 31 января 2020

Нет необходимости в дополнительном подзапросе или CTE. Вы можете повернуть свой набор данных с помощью условного агрегирования с небольшими изменениями вашего запроса: просто удалите shift из предложения group by, а затем внедрите условные логики c в sum() s:

select
  date,
  sum(case when shift = 1 then value end) shift1,
  sum(case when shift = 2 then value end) shift2,
  sum(case when shift = 3 then value end) shift3
from
  db.table
where
  date >= date '2020-01-01'
  and filter = 'type'
group by date
order by date

Примечание:

  • нет необходимости добавлять префиксы к именам столбцов, поскольку в игру вступает одна таблица. Я удалил эти

  • date - это имя типа данных в Oracle, поэтому не очень хороший выбор для имени столбца

1 голос
/ 31 января 2020

Вы можете сделать условное агрегирование:

select t.date,
       sum(case when t.shift = 1 then t.value else 0 end),
       sum(case when t.shift = 2 then t.value else 0 end),
       sum(case when t.shift = 3 then t.value else 0 end)
from db.table as t
where t.date >= date '2020-01-01' and
      t.filter = 'type'
group by t.date;
0 голосов
/ 31 января 2020

Вы можете использовать PIVOT для этого следующим образом:

SELECT
    *
FROM ( SELECT
  table.date,
  table.shift,
  table.value
from
  db.table
where
  table.date >= date '2020-01-01' and
  table.FILTER = 'type' ) 
  PIVOT 
  ( SUM ( VALUE ) FOR SHIFT IN ( 1,2,3 ))
ORDER BY date;

Приветствия !!

0 голосов
/ 31 января 2020

Вы можете использовать условное агрегирование

with cte as
(
select
  table.date,
  table.shift,
  sum(table.value) as val
from
  db.table
where
  table.date >= date '2020-01-01' and
  table.filter = 'type'
group by
  table.date,
  table.shift
order by
  table.date,
  table.shift
)
select date, max(case when shift=1 then val end) as 1,
max(case when shift=1 then val end) as 2,
max(case when shift=1 then val end) as 3
from cte
group by date
...