代码之家  ›  专栏  ›  技术社区  ›  JacobIRR

如何使用groupby和/或having从表中获取复制

  •  0
  • JacobIRR  · 技术社区  · 6 年前

    如果我有这张桌子:

    id | aux_id | name
    ------------------
    1  | 22     | foo
    2  | 22     | bar
    3  | 19     | baz
    

    如何得到这个结果,显示共享 aux_id

    name
    ----
    foo
    bar
    

    GROUP BY HAVING 但这不起作用:

    SELECT name FROM my_table
    GROUP BY aux_id
    HAVING COUNT(aux_id) > 1
    

    列“name”在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

    4 回复  |  直到 6 年前
        1
  •  3
  •   Gordon Linoff    6 年前

    怎么样 exists

    select t.name
    from my_table t
    where exists (select 1
                  from my_table t2
                  where t2.aux_id = t.aux_id and t2.name <> t.name
                 );
    
        2
  •  2
  •   Yogesh Sharma    6 年前

    我会用 exists :

    select t.name
    from table t
    where exists (select 1 from table t1 where t1.aux_id = t.aux_id and t1.id <> t.id);
    

    group by

        3
  •  1
  •   MatBailie    6 年前

    另一个选择,只是为了好玩。。。

    WITH
      duplication_counts AS
    (
      SELECT
        *,
        COUNT(*) OVER (PARTITION BY aux_id)   AS aux_id_occurrences
      FROM
        my_table
    )
    SELECT
      *
    FROM
      duplication_counts
    WHERE
      aux_id_occurrences > 1
    
        4
  •  1
  •   Cetin Basoz    6 年前

    select * from myTable 
    where aux_id in 
      (select aux_id 
       from myTable 
       group by aux_id 
       having count(*) > 1)
    

    SQLFiddle Demo