我想要的是计算对应于真(出勤),假(非出勤)和任何单个事件的NULL的数组元素.
编辑:
我刚刚意识到数组的行为与我在psql中的行为不同,所以很简单
userconfirm bool[]
可能就够了.但是,我仍然在计算true / false / null值时遇到同样的问题.我将尝试编辑下面的问题以匹配此新约束.我为任何错误道歉.
我有一个专栏如
userconfirm bool[]
userconfirm [314] = true表示用户#314将参加. (false =没有参加,NULL =没有阅读/等).
我不确定这是否是此功能的最佳解决方案(用户宣布他们参加活动),但我在此专栏上遇到了聚合功能问题.
select count(*) from foo where id = 6 AND true = ANY (userconfirm);
这只返回1,并试图谷歌“计数数组”没有出现任何有用的东西.
我如何计算单个事件的不同值?
解决方法
您可以在SELECT中使用
unnest
,如下所示:
select whatever,(select sum(case b when 't' then 1 else 0 end) from unnest(userconfirm) as dt(b)) from your_table -- ...
例如,鉴于此:
=> select * from bools; id | bits ----+-------------- 1 | {t,t,f} 2 | {t,f} 3 | {f,f} 4 | {t,t} 5 | {f,NULL}
你会得到这个:
=> select id,(select sum(case b when 't' then 1 else 0 end) from unnest(bits) as dt(b)) as trues from bools; id | trues ----+------- 1 | 2 2 | 1 3 | 0 4 | 3 5 | 2
如果那太难看了,你可以编写一个函数:
create function count_trues_in(boolean[]) returns bigint as $$ select sum(case b when 't' then 1 else 0 end) from unnest($1) as dt(b) $$language sql;
并用它来完成你的查询:
=> select id,count_trues_in(bits) as trues from bools; id | trues ----+------- 1 | 2 2 | 1 3 | 0 4 | 3 5 | 2