postgresql - 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
但我想知道他们是否不是获得相同结果的更有效(更快)的方式。
谢谢
解决方案
您可以通过条件聚合使用单个查询/传递表:
select
sum(weight) filter (where istrue) as istrue,
sum(weight) filter (where not istrue) as isnottrue
from toto
into var_istrue, var_isnottrue;
推荐阅读
- bash - 码头工人执行卷曲帖子
- java - BufferedReader 无法读取 Google Cloud Storage ReadChannel 上的所有行
- android - 在 Android 中响应耳机上的媒体按钮
- redirect - 如何将托管在同一服务器上的域重定向到另一个域的子页面
- excel - 与最近发生相对应的列出的 Product_ID 的 2 个最近费率
- flutter - 即使在 setState 调用之后,Gridview 也不会更新
- java - 如何将 JSONArray 转换为 Java 字符串数组
- javascript - 如何在使用 JavaScript 的移动过程中将移动替换为另一个移动?
- elasticsearch - 如何生成 gce 凭据
- arrays - 查询嵌套的子文档数组