我有如下表格:
ID array1 array2
7333 | {615593} | {NULL}
7333 | {2013682} | {NULL}
7333 | {26573,1508291} | {NULL}
7333 | {1457957} | {NULL}
7333 | {NULL} | {1063105}
7333 | {NULL} | {107978,408431}
我想为每个 edge_id 查询 array1 和 array2 的所有唯一项目。例如
ID array1_distinct array2_distinct
7333 5 3
我试过类似下面的方法
SELECT
id,
array1_count
FROM (
SELECT id,
COUNT(DISTINCT((CASE WHEN array1 is not null THEN (select unnest(array1)b) END)) as array1_count
FROM mytable
GROUP BY id
) totals
limit 1
在尝试使用 unnest 对数组中的元素进行计数时,我总是会遇到诸如“用作表达式的子查询返回的多行”和“在无法接受集合的上下文中调用的集值函数”之类的错误。
最佳答案
select id, count(distinct a1) as a1, count(distinct a2) as a2
from (
select id, unnest(array1) as a1, unnest(array2) as a2
from t
) s
group by id
关于arrays - Postgres : How to count distinct elements in array columns given a condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25463662/