gpt4 book ai didi

PostgreSQL 计数( bool 表达式)

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

在 Postgresql 中最好的方法是什么,我想计算字段 A 中有多少个 value = 1 以及同一字段中有多少个 value = 0 A.

像这样:

select 
count (field1 = value1) as filed1_ok,
count (field1 = value2) as filed1_bad,
extract(MONTH from rpt_date) AS mth
where rpt_date between frdate and todate
group by mth

最佳答案

使用count(condition or null)

select
count(field1 = 1 or null) as filed1_ok,
count(field1 = 0 or null) as filed1_bad,
extract(MONTH from rpt_date) AS mth
where rpt_date between frdate and todate
group by mth

true or null 的计算结果为 truefalse 或 null 的计算结果为 null。由于 count 不计算空值,这正是您想要的。

在其他 SQL 方言和 Postgresql 中,可以使用 case

select
coalesce(sum(case field1 when 1 then 1 end), 0) as filed1_ok,
coalesce(sum(case field1 when 0 then 1 end), 0) as filed1_bad,
extract(MONTH from rpt_date) AS mth
where rpt_date between frdate and todate
group by mth

count(condition or null) Postgresql 选项相比,我认为它冗长且不透明。

关于PostgreSQL 计数( bool 表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25818713/

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