Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL:将两个计数查询合并为一个_Sql_Postgresql - Fatal编程技术网

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

目前,我有两个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

但它仍然只返回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;