我可以在一个查询中对结果进行一次选择,然后进行不同的选择吗?
现在我想做类似的事情(不起作用)
select
(select count(*), sum(amount) from view where amount > 5),
(select count(*), sum(amount) from view where amount < 5)
from
(select id, amount from warehouse where createDate = '2019-01-01') as view;
我不想选择视图,然后再基于该视图选择一些数据并进行其他过滤。
答案 0 :(得分:3)
您可以使用条件聚合:
select count(*),
sum(amount) filter (where waga > 5),
sum(amount) filter (where amount < 5)
from warehouse
where createdate = date '2019-01-01'
答案 1 :(得分:1)
关于可以使用WITH子句的一般语法问题:
with v as
(
select id, amount from warehouse where createDate = '2019-01-01'
)
select * from
(
(select count(*), sum(amount) from v where waga > 5) as count1,
(select count(*), sum(amount) from v where amount < 5) as count2
);
(我并不是说它会更快;这只是使用“内联”视图的一种方式。)