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

使用Distinct和Group By的Oracle SQL

  •  1
  • user3128376  · 技术社区  · 7 年前

    我下面有张桌子

    +-----+------+-----------+------------+
    | id  | type | last_name | first_name |
    +-----+------+-----------+------------+
    |   1 | A    | Billy     | John       |
    |   2 | B    | Bob       | Joe        |
    |   3 | A    | Joe       | Zeb        |
    |   4 | C    | Billy     | John       |
    | ... | ...  | ...       | ...        |
    +-----+------+-----------+------------+
    

    LAST_NAME FIRST_NAME ,但有不同的 TYPE .

    类型 ?

    我想回报的是:

    +-----+------+-----------+------------+
    | id  | type | last_name | first_name |
    +-----+------+-----------+------------+
    |   1 | A    | Billy     | John       |
    |   4 | C    | Billy     | John       |
    | ... | ...  | ...       | ...        |
    +-----+------+-----------+------------+
    
    3 回复  |  直到 7 年前
        1
  •  1
  •   Lee Mac    7 年前

    下面是一种使用相关子查询的可能方法:

    select t.*
    from table1 t
    where exists 
    (
        select 1 from table1 u
        where 
        u.last_name = t.last_name and 
        u.first_name = t.first_name and 
        u.type <> t.type
    )
    

    或者,可能使用联接:

    select t.*
    from table1 t inner join
    (
        select u.last_name, u.first_name
        from table1 u
        group by u.last_name, u.first_name
        having min(u.type) <> max(u.type)
    ) q 
    on t.last_name = q.last_name and t.first_name = q.first_name
    

    改变 table1

        2
  •  0
  •   holger abend    7 年前

    也许我监督了一些事情。你怎么看:

    select * from table
    group by last_name, first_name
    having count(type) = 1
    
        3
  •  0
  •   GMB    7 年前

    SELECT x.id, x.type, x.last_name, x.first_name
    FROM (
        SELECT t.*, COUNT(DISTINCT type) OVER (PARTITION BY last_name, first_name) cnt
        FROM mytable t
    ) x WHERE x.cnt > 1
    

    内部查询为每个记录分配当前名字/姓氏元组的不同类型的计数,外部查询以1的计数筛选出行。

    Demo on DB Fiddle :

    ID | TYPE | LAST_NAME | FIRST_NAME
    -: | :--- | :-------- | :---------
     1 | A    | Billy     | John      
     4 | C    | Billy     | John