sql - 在PostgreSQL中将两个或多个不同的SELECT查询组合到具有不同条件的同一张表中
问题描述
我需要从同一个表中检索两个不同的结果,并将它们组合成一个结果集。我正在使用聚合函数来生成有关某些数据的报告,并且每一列都有不同的“位置”条件。
select sum(price)
as lucro_esperado
from tasks
where extract(month from enddate) = 12
AND extract(year from enddate) = 2019
和
select count(*)
as tarefas_abertas
from tasks
where extract(month from date_added) = 12
AND extract(year from date_added) = 2019
由于我对这种情况感兴趣的是聚合函数结果,因此我无法使用 Join 语句(因为没有ON条件),而 Union 语句会抱怨不同的数据类型,因为它试图错误地合并两个聚合结果成一列。有什么其他方法可以实现这一点,而不必从我的 Node.js 端点查询数据库两次,然后手动组合它们?
解决方案
只需将其写为一个查询:
select sum(price) as lucro_esperado, count(*) as tarefas_abertas
from tasks
where extract(month from enddate) = 12 and
extract(year from enddate) = 2019
我建议您将where
条款更改为:
where enddate >= '2019-12-01' and
enddate < '2020-01-01'
这允许数据库使用索引enddate
(如果可用)。此外,删除列上的函数调用有助于优化器。
编辑:
我明白了,这两个日期参数是不同的。只需使用条件聚合:
select sum(case when enddate >= '2019-12-01' and enddate < '2020-01-01' then price end) as lucro_esperado,
sum(case when date_added >= '2019-12-01' and date_added < '2020-01-01' then 1 else 0 end) as tarefas_abertas
from tasks;
推荐阅读
- python - 如何将带有文件的数据上传到 Flask 应用程序?
- node.js - Mongodb 找不到具有特定字段的文档
- haskell - 用 foldr 在二叉树中找到具有最小值的节点
- python - Windows 上使用 MQTT 的 SSLCertVerificationError
- kubernetes - 如何在 Pod Kubernetes 中查看历史
- javascript - 使用 HtmlUnit 导航到 javascript 表单
- python - 如何在 Seaborn 中绘制这种图表?
- mysql - 在“WHERE A AND B”中,如果A为假,mysql会检查B吗?
- c++ - 为什么 wxSound 不发出声音?构建日志上没有错误
- javascript - 如何将对象数组及其属性导出到另一个 JS 文件?