如何使用postgresql中的不同WHERE语句按group by进行两次单独计数?

如何使用postgresql中的不同WHERE语句按group by进行两次单独计数?,postgresql,Postgresql,我有两个单独的问题,只是在“WHERE”语句中有所不同: SELECT concat(extract(MONTH from created_at),'-', extract(year from created_at)) AS "Month", count(email) AS "Total AB Signups" from users where is_accountant='t' group by 1,extract(month from created_at),extract(year fr

我有两个单独的问题,只是在“WHERE”语句中有所不同:

SELECT concat(extract(MONTH from created_at),'-', extract(year from created_at)) AS "Month", 
count(email) AS "Total AB Signups"
from users
where is_accountant='t'
group by 1,extract(month from created_at),extract(year from created_at)
order by extract(year from created_at),extract(month from created_at);
然后:

如何将其合并到一个如下所示的表中:

Month | Total AB Signups | Total SMB Signups
---------------------------------------------

您可以将
where
条件移动到count函数中的
case
表达式:

SELECT concat(extract(MONTH from created_at),'-', extract(year from created_at)) AS "Month", 
count(case when is_accountant='t' then email end) AS "Total AB Signups",
count(case when is_accountant='f' then email end) AS "Total SMB Signups"
from users
group by 1,extract(month from created_at),extract(year from created_at)
order by extract(year from created_at),extract(month from created_at);
或者,如果您使用的是Postgresql 9.4+,则可以使用新的
过滤器
语法:

SELECT concat(extract(MONTH from created_at),'-', extract(year from created_at)) AS "Month", 
count(email) FILTER (where is_accountant='t') AS "Total AB Signups",
count(email) FILTER (where is_accountant='f') AS "Total SMB Signups"
from users
group by 1,extract(month from created_at),extract(year from created_at)
order by extract(year from created_at),extract(month from created_at);

在第二次查询中,列名也是
Total AB Signups
,但在所需结果中是
Total SMB Signups
;我猜这是一个打字错误,不是故意的?非常感谢!这非常有帮助。顺便说一句,你介意看看我今天发布的其他问题吗?
SELECT concat(extract(MONTH from created_at),'-', extract(year from created_at)) AS "Month", 
count(email) FILTER (where is_accountant='t') AS "Total AB Signups",
count(email) FILTER (where is_accountant='f') AS "Total SMB Signups"
from users
group by 1,extract(month from created_at),extract(year from created_at)
order by extract(year from created_at),extract(month from created_at);