arrays - Postgres : How to count distinct elements in array columns given a condition

标签 arrays postgresql count distinct

我有如下表格:

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/

相关文章:

javascript - 有没有办法打印我的 clickCount 而不是使用 <input> 标签

php - 在 PHP MySQL 上显示、连接、计数、分组 6 个表

python - Python 中的算术级数而不存储所有值

python - 使用置换向量对矩阵重新排序,但保持矩阵的原始大小

postgresql - 使用 vagrant & puppet,如何在新的 postgresql-server 实例上创建和恢复数据库?

sql - Coalesce 和 Case-When with To_Date 没有按预期工作(Postgres 错误?)

SQL:如何根据不同表中的记录从一个表中选择多条记录的计数?

javascript - Parse.com 查询指针数组时出现问题,.include 未在云代码中获取嵌套指针数据

PHP 将值 1 添加到数组中的某个位置

postgresql - 从一组表左连接到postgresql中的另一组表