Find duplicated values on array column

删除回忆录丶 提交于 2019-12-20 02:57:13

问题


I have a table with a array column like this:

my_table
id   array
--   -----------
1    {1, 3, 4, 5}
2    {19,2, 4, 9}
3    {23,46, 87, 6}
4    {199,24, 93, 6}

And i want as result what and where is the repeated values, like this:

value_repeated    is_repeated_on
--------------    -----------
4                 {1,2}
6                 {3,4}

Is it possible? I don't know how to do this. I don't how to start it! I'm lost!


回答1:


Use unnest to convert the array to rows, and then array_agg to build an array from the ids

It should look something like this:

SELECT v AS value_repeated,array_agg(id) AS is_repeated_on FROM 
(select id,unnest(array) as v from my_table) 
GROUP by v HAVING Count(Distinct id) > 1

Note that HAVING Count(Distinct id) > 1 is filtering values that don't appear even once




回答2:


The clean way to call a set-returning function like unnest() is in a LATERAL join, available since Postgres 9.3:

SELECT value_repeated, array_agg(id) AS is_repeated_on
FROM   my_table
     , unnest(array_col) value_repeated
GROUP  BY value_repeated
HAVING count(*) > 1
ORDER  BY value_repeated;  -- optional

About LATERAL:

  • Call a set-returning function with an array argument multiple times

There is nothing in your question to rule out shortcut duplicates (the same element more than once in the same array (like I@MSoP commented), so it must be count(*), not count (DISTINCT id).



来源:https://stackoverflow.com/questions/29897501/find-duplicated-values-on-array-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!