首页 > 解决方案 > posgresql 10 如何将过滤后的总和结果分配给不同的变量?

问题描述

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

这里我的表toto是真实的|重量| ------|--------| 假 |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

但我想知道他们是否不是获得相同结果的更有效(更快)的方式。

谢谢

标签: postgresqlplsql

解决方案


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

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

推荐阅读