我有如下查询:
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
无需添加子查询或CTE。您可以使用条件聚合来对数据集进行透视,并对查询进行一些修改:只需shift
从group 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中数据类型的名称,因此不是列名的好选择
这个答案是最适合我需要的答案,所以我会接受的。难道不期望西方有这么快的枪支吗,更像是我找不到的某个问题的重复副本,或者是“您搜索了吗?” 有点指责。谢谢。