[英]PostgreSQL count array values
我想要的是計算對應於真(出勤),假(非出勤)和任何單個事件的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,t}
5 | {f,t,t,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
你可以使用array_length函數結果:
SELECT SUM(array_length(userconfirm, 2)) WHERE id = 6;
這一個可以做的伎倆( UNNEST )。
postgres=# with y(res) as (
postgres(# with x(a) as (
postgres(# values (ARRAY[true,true,false])
postgres(# union all
postgres(# values (ARRAY[true,null,false])
postgres(# )
postgres(# select unnest(a) as res
postgres(# from x
postgres(# )
postgres-# select count(*)
postgres-# from y
postgres-# where res;
count
-------
3
(1 row)
postgres=#
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.