gpt4 book ai didi

postgresql - 如何在 postgresql 中使用不同的 WHERE 语句按组进行两个单独的计数?

转载 作者:行者123 更新时间:2023-11-29 13:26:30 25 4
gpt4 key购买 nike

我有两个单独的查询,它们仅在“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);

然后:

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='f'
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+,则可以使用新的 filter 语法:

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);

关于postgresql - 如何在 postgresql 中使用不同的 WHERE 语句按组进行两个单独的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32895614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com