posgresql 10 如何将过滤后的总和结果分配给不同的变量?



我尝试在同一表中的同一查询中,根据不同的过滤条件分配总和的结果。

这是我的表多多 是真的|重量| ------|------| 假 |0.1500| 真 |0.1319| 真 |0.0002| 假 |0.0001| 真 |0.0435|

一个简单的选择给我预期的结果.....

select (select sum(weight) from toto where istrue) as istrue,
(select sum(weight) from toto where not istrue) as isnottrue;
|istrue |isnottrue |
|-------|----------|
|0.1756 |0.1501    |

现在我想将这 2 列分配给 2 个变量....

DO $$
declare
var_istrue numeric(6,4) := 0.0;
var_isnottrue numeric(6,4) := 0.0;
begin
select (select sum(weight) from toto where istrue) as istrue,
(select sum(weight) from toto where not istrue) as isnottrue 
into var_istrue, 
var_isnottrue;
raise notice ' isTrue=%',var_istrue;
raise notice ' isNOTTrue=%',var_isnottrue;
end $$;

并获得预期的结果:

00000:  isTrue=0.1756
00000:  isNOTTrue=0.1501

但我想知道是否有更有效(更快(的方法来获得相同的结果。

谢谢

您可以使用单个查询/传递表和条件聚合:

select
sum(weight) filter (where istrue) as istrue,
sum(weight) filter (where not istrue) as isnottrue 
from toto
into var_istrue, var_isnottrue;

最新更新