我需要像 PostgreSQL 中的 countif 这样的函数

I need a function like countif in PostgreSQL

我有这个table像这样

Status    Last_update_time
4      | 2/2/2021, 11:03
5      | 2/2/2021, 12:04
4      | 24/2/2021, 12:36
4      | 20/2/2021, 17:33
5      | 13/2/2021, 10:57

我已经写了一个SQL这样的

Select date_trunc('week', CAST(kyc.last_update_time as timestamp )) AS "week",
       Count(status)
From KYC
Where kyc.status = 4 
  and (kyc.last_update_time >= date_trunc('week', CURRENT_TIMESTAMP - interval '3 week') 
       and kyc.last_update_time < date_trunc('week', CURRENT_TIMESTAMP))
Group by 1

所以我在过去 3 周内每周的状态都为 4

但现在我想改变我可以数 4 和 5。当我可视化时,我将有 2 列,1 列用于状态 4,1 列用于状态 5

我的预期输出 SQL 像这样

Select date_trunc('week', CAST(kyc.last_update_time as timestamp )) AS "week",
       Count(if(kyc.status = 4,kyc.used_id,null) as XTTC
       Count(if(kyc.status = 5,kyc.used_id,null) as XTTB
From KYC 

Where (kyc.last_update_time >= date_trunc('week', CURRENT_TIMESTAMP - interval '3 week') 
       and kyc.last_update_time < date_trunc('week', CURRENT_TIMESTAMP))
Group by 1

excel 中是否有类似 countif 的函数可以帮助我解决这个问题

谢谢

正如@a_horse_with_no_name 所建议的那样,您可以使用条件 aggregation with filter 作为 countif 的一种非常有效的替代方法来实现这一点。

select date_trunc('week', last_update_time::timestamp) as "week", 
       count(*) filter (where status = 4) as "XTTC",
       count(*) filter (where status = 5) as "XTTB"
from kyc
where last_update_time >= date_trunc('week', CURRENT_TIMESTAMP - interval '3 weeks') 
  and last_update_time <  date_trunc('week', CURRENT_TIMESTAMP)
group by 1;