期间每个月的总数

时间:2015-06-11 12:49:27

标签: postgresql

鉴于这种情况,我有以下就业记录

id | user_id   |  Month          | Active
1  | 1         |  June 2014      | true
2  | 1         |  September 2014 | false
3  | 2         |  June 2014      | true

如何进行查询以返回每月的活跃用户总数,返回数据应为:

active_count | month
2            | June 2014
2            | July 2014
2            | August 2014
1            | September 2014

非常感谢任何帮助

2 个答案:

答案 0 :(得分:2)

您正在寻找条件聚合:

SELECT count(case when active then 1 end) as active_count,
       month
FROM employment 
GROUP BY month;

使用Postgres 9.4,使用filter()运算符可以更简洁地写出来:

SELECT count(*) filter (where active) as active_count,
       month
FROM employment 
GROUP BY month;

答案 1 :(得分:0)

这是SQL查询尝试这个

SELECT  
    count(id) active_count,
    month
FROM
    employment 
GROUP BY
    month;