在数组列上查找重复值
Find duplicated values on array column
我有一个 table 的数组列如下:
my_table
id array
-- -----------
1 {1, 3, 4, 5}
2 {19,2, 4, 9}
3 {23,46, 87, 6}
4 {199,24, 93, 6}
我想要的结果是重复值是什么以及在哪里,就像这样:
value_repeated is_repeated_on
-------------- -----------
4 {1,2}
6 {3,4}
可能吗?我不知道该怎么做。我不知道如何开始它!我迷路了!
使用 unnest
将数组转换为行,然后 array_agg
从 id
s
构建数组
它应该看起来像这样:
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
请注意,HAVING Count(Distinct id) > 1
正在过滤一次都没有出现的值
像 unnest()
这样调用集合返回函数的简洁方法是在 LATERAL
连接中,自 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
关于LATERAL
:
- Call a set-returning function with an array argument multiple times
你的问题中没有任何东西可以排除快捷方式重复(同一个元素在同一个数组中不止一次(),所以它必须是count(*)
,而不是count (DISTINCT id)
.
我有一个 table 的数组列如下:
my_table
id array
-- -----------
1 {1, 3, 4, 5}
2 {19,2, 4, 9}
3 {23,46, 87, 6}
4 {199,24, 93, 6}
我想要的结果是重复值是什么以及在哪里,就像这样:
value_repeated is_repeated_on
-------------- -----------
4 {1,2}
6 {3,4}
可能吗?我不知道该怎么做。我不知道如何开始它!我迷路了!
使用 unnest
将数组转换为行,然后 array_agg
从 id
s
它应该看起来像这样:
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
请注意,HAVING Count(Distinct id) > 1
正在过滤一次都没有出现的值
像 unnest()
这样调用集合返回函数的简洁方法是在 LATERAL
连接中,自 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
关于LATERAL
:
- Call a set-returning function with an array argument multiple times
你的问题中没有任何东西可以排除快捷方式重复(同一个元素在同一个数组中不止一次(count(*)
,而不是count (DISTINCT id)
.