编辑:
我刚刚意识到数组的行为与我在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() 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总结
以上是内存溢出为你收集整理的PostgreSQL计数数组值全部内容,希望文章能够帮你解决PostgreSQL计数数组值所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)