【问题标题】:Find duplicated values on array column在数组列上查找重复值
【发布时间】:2015-04-27 13:42:42
【问题描述】:

我有一个这样的数组列:

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}

有可能吗?我不知道该怎么做。我不知道怎么开始!我迷路了!

【问题讨论】:

    标签: sql arrays postgresql aggregate-functions set-returning-functions


    【解决方案1】:

    使用unnest 将数组转换为行,然后使用array_aggids 构建数组

    它应该看起来像这样:

    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 正在过滤甚至不出现一次的值

    【讨论】:

    • 请注意,正如目前所写的,这将显示所有可能的值;要仅显示至少出现在两个地方的那些,您需要添加一个 HAVING 子句,例如HAVING Count(Distinct id) > 1,或者只是HAVING Count(*) > 1,如果你确定同一个数字永远不会在同一个数组中出现两次。
    • 非常感谢!完美!
    【解决方案2】:

    调用像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

    您的问题中没有任何内容可以排除快捷方式重复(同一个元素在同一个数组中多次出现 (like I@MSoP commented),因此它必须是 count(*),而不是 count (DISTINCT id)

    【讨论】:

    • 更简洁直观。
    猜你喜欢
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 2012-05-04
    • 2016-08-31
    • 2015-09-24
    • 1970-01-01
    相关资源
    最近更新 更多