首页 > 解决方案 > 在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 端点查询数据库两次,然后手动组合它们?

标签: sqlnode.jspostgresqlexpress

解决方案


只需将其写为一个查询:

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;

推荐阅读