我有如下查询:
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
您可以使用条件聚合
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
不需要附加子查询或CTE。
您可以使用条件聚合来对数据集进行透视,并稍加修改您的查询:只需从shift
子句中删除group by
,然后在sum()
s中实现条件逻辑:
select
t.date,
sum(case when t.shift = 1 then t.value end) shift1,
sum(case when t.shift = 2 then t.value end) shift2,
sum(case when t.shift = 3 then t.value end) shift3
from
db.table t
where
t.date >= date '2020-01-01' and
t.filter = 'type'
group by t.date
order by t.date
您可以进行条件聚合:
select t.date,
sum(case when table.shift = 1 then table.value else 0 end),
sum(case when table.shift = 2 then table.value else 0 end),
sum(case when table.shift = 3 then table.value else 0 end)
from db.table as t
where t.date >= date '2020-01-01' and
t.filter = 'type'
group by t.date;