温馨提示:本文翻译自stackoverflow.com,查看原文请点击:sql - Split column into multiple columns by criteria
group-by oracle pivot sql oracle11g

sql - 按条件将列拆分为多列

发布于 2020-03-27 16:19:34

我有如下查询:

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 

查看更多

提问者
user7393973
被浏览
125
GMB 2020-01-31 17:20

无需添加子查询或CTE。您可以使用条件聚合来对数据集进行透视,并对查询进行一些修改:只需shiftgroup by子句中删除,然后在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中数据类型的名称,因此不是列名的好选择