使用Distinct和Group By的Oracle SQL

使用Distinct和Group By的Oracle SQL,sql,oracle,Sql,Oracle,我在下面有一张桌子 +-----+------+-----------+------------+ | id | type | last_name | first_name | +-----+------+-----------+------------+ | 1 | A | Billy | John | | 2 | B | Bob | Joe | | 3 | A | Joe | Zeb |

我在下面有一张桌子

+-----+------+-----------+------------+
| id  | type | last_name | first_name |
+-----+------+-----------+------------+
|   1 | A    | Billy     | John       |
|   2 | B    | Bob       | Joe        |
|   3 | A    | Joe       | Zeb        |
|   4 | C    | Billy     | John       |
| ... | ...  | ...       | ...        |
+-----+------+-----------+------------+
我想返回所有具有相同姓氏和姓氏但类型不同的记录

我是否需要执行子查询以首先获得相同的名称,然后对其进行类型筛选

我想回报的是:

+-----+------+-----------+------------+
| id  | type | last_name | first_name |
+-----+------+-----------+------------+
|   1 | A    | Billy     | John       |
|   4 | C    | Billy     | John       |
| ... | ...  | ...       | ...        |
+-----+------+-----------+------------+

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

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

更改表1以适合您的表名。

也许我监督了一些事情。您认为:

select * from table
group by last_name, first_name
having count(type) = 1

这应该是使用窗口函数的简单方法,从早期版本开始,Oracle中就提供了窗口函数:

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的行

:

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