我有以下查询:
select a.user_id, sum(c.amount) as all_assets,
sum(case when b.class='x' then c.amount end) assets_x,
sum(case when b.class='y' then c.amount end) assets_y,
sum(case when b.class='z' and c.amount<=100 then c.amount end) assets_z
from a
join b on a.id=b.id
join c on b.id=c.id
group by a.user_id
按用户ID对资产进行分组,并将总资产分为x,y和z类,其中类z和仅z排除c.amount >100
的主语。
我的问题是,在计算all_assets时,如何从总数中移除c.amount>100
b.class='z'
的主菜?
答案 0 :(得分:2)
如果要对select
的所有部分执行此操作,请使用where
子句:
select a.user_id, sum(c.amount) as all_assets,
sum(case when b.class = 'x' then c.amount end) as assets_x,
sum(case when b.class = 'y' then c.amount end) as assets_y,
sum(case when b.class = 'z' and c.amount <= 100 then c.amount end) as assets_z
from a join
b
on a.id = b.id join
c
on b.id = c.id
where not (b.class = 'z' and c.amount > 100)
group by a.user_id;
您还可以将此短语称为另一个条件聚合:
select a.user_id,
sum(case when b.class in ('x', 'y') or c.amount <= 100 then c.amount end) as all_assets,
sum(case when b.class = 'x' then c.amount end) as assets_x,
sum(case when b.class = 'y' then c.amount end) as assets_y,
sum(case when b.class = 'z' and c.amount <= 100 then c.amount end) as assets_z
from a join
b
on a.id = b.id join
c
on b.id = c.id
group by a.user_id;
此版本假设唯一的类是x,y和z。