根据操作员条件按值分组-Postgres

时间:2020-07-28 21:00:02

标签: sql postgresql count pivot

我有一个表格,该表格中的值是根据客户是否点击了虚构的网站而进行了点击。我想比较那些拥有/没有的人的分布情况,如下表:

gender  country clicks
male    US  1
male    US  0
male    US  3
male    US  2
female  US  1
female  US  0
female  US  0

输出应为:

gender  country notclicked clicked
female  US      2          1
male    US      1          3

但是我能确定的唯一方法是通过两个单独的查询并将它们添加在一起,手动

select gender, country, count(clicks) as not_clicked from performance
where clicks = 0
group by gender, country;

select gender, country, count(clicks) as clicked from performance
where clicks >= 1
group by gender, country;

如何使此查询更智能并一次性运行?

在下面提供有关表模式和查询的信息

SQL Fiddle

谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用:

select gender, country, sum(1 - clicks) as not_clicked, sum(clicks) as clicked
from performance
where clicks = 0
group by gender, country;

看起来clicks是一个采用01值的数字。

通常,我会推荐filter

select gender, country, 
       count(*) filter (where clicked = 0) as not_clicked,
       count(*) filter where click = 1) as clicked
from performance
where clicks = 0
group by gender, country;

答案 1 :(得分:0)

您的数据和结果与您对问题的描述完全不符。根据您现有的查询,我认为您需要条件聚合:

select
    gender,
    country,
    count(*) filter(where clicks = 0) not_clicked,
    count(*) filter(where clicks > 0) clicked
from performance
group by gender, country