【问题标题】:SQL: Combine two count queries into oneSQL:将两个计数查询合二为一
【发布时间】:2020-09-18 04:02:57
【问题描述】:

目前我有两个 sql 查询,每个查询都返回特定日期特定列的总数:

select first_name COUNT(*) as totalCount from some_table
where the_date >= '2020-09-14' and the_date <='2020-09-15' 
group by first_name

select first_name COUNT(*) as totalCount from some_table
where the_date >= '2020-09-16' and the_date <='2020-09-17' 
group by first_name

每个都会返回一个表格,例如:

first_name | totalCount

相反,我想要一个返回结果的查询:

first_name | count1 | count2

count1 是第一个查询的总计数,count2 是第二个查询的总计数

我试过了:

select first_name COUNT(*) as count1 from some_table
where the_date >= '2020-09-14' and the_date <='2020-09-15' 
group by first_name
UNION
select first_name COUNT(*) as count2 from some_table
where the_date >= '2020-09-16' and the_date <='2020-09-17' 
group by first_name

但它仍然只返回count1的结果。

【问题讨论】:

  • 你试过UNION吗?
  • @Mech 我做了,让我添加我尝试过的内容

标签: sql postgresql


【解决方案1】:

使用条件聚合:

SELECT
    first_name,
    COUNT(*) FILTER (WHERE the_date >= '2020-09-14' AND the_date < '2020-09-15') AS totalCount1,
    COUNT(*) FILTER (WHERE the_date >= '2020-09-16' AND the_date < '2020-09-17') AS totalCount2
FROM some_table
GROUP BY
    first_name;

请注意,我使用的不等式如下所示:

the_date >= '2020-09-14' AND the_date < '2020-09-15'

这将只针对日期'2020-09-14'。

编辑:

对于您在下面的 cmets 中的后续问题,如果您想匹配两个计数均为零的名字,请使用:

SELECT
    first_name
FROM some_table
GROUP BY
    first_name
HAVING
    COUNT(*) FILTER (WHERE the_date >= '2020-09-14' AND the_date < '2020-09-15' OR
                           the_date >= '2020-09-16' AND the_date < '2020-09-17') = 0;

【讨论】:

  • 这太棒了!!当totalCount1和totalCount2同时为0时如何过滤掉?
  • @MohamadZein 检查更新的答案,希望这会有所帮助。
  • 哦,我的意思是从你写的第一个查询中,我想过滤掉 totalCount1 列和 totalCount2 列都为 0 的行(当两者同时)
  • ...我的答案底部的查询是这样做:-)
猜你喜欢
  • 2014-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
相关资源
最近更新 更多