SQL:将两个计数查询合并为一个
目前,我有两个sql查询,每个查询返回特定日期特定列的总计数:SQL:将两个计数查询合并为一个,sql,postgresql,Sql,Postgresql,目前,我有两个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 &g
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
但它仍然只返回count1的结果。使用条件聚合:
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;
使用条件聚合:
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;
你试过联合吗?@Mech我试过,让我加上我试过的。你试过联合吗?@Mech我试过,让我加上我试过的。这太棒了!!当totalCount1和totalCount2同时为0时,我如何过滤掉呢?@MohamadZein检查更新的答案,希望这有帮助。哦,我是说,从你写的第一个查询中,我想过滤掉totalCount1列和totalCount2列同时为0的行…我的答案底部的查询是这样做的:-这太棒了!!当totalCount1和totalCount2同时为0时,我如何过滤掉呢?@MohamadZein检查更新的答案,希望这有帮助。哦,我是说,从你写的第一个查询中,我想过滤掉totalCount1列和totalCount2列同时为0的行……我的答案底部的查询是这样做的:-
the_date >= '2020-09-14' AND the_date < '2020-09-15'
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;