Oracle SQL使用不同和分组依据

时间:2019-01-30 22:45:20

标签: sql oracle

我在下表中

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

我想返回所有具有相同LAST_NAMEFIRST_NAME但具有不同TYPE的记录。

我是否需要进行子查询以首先获取相同的名称,然后为TYPE对其进行过滤?

我想返回的内容:

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

3 个答案:

答案 0 :(得分:1)

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

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以适合您的表名。

答案 1 :(得分:0)

也许我监督了一些事情。您如何看待:

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

答案 2 :(得分:0)

使用窗口函数应该很简单,该函数从早期版本开始就在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的行拟合出来。

Demo on DB Fiddle

ID | TYPE | LAST_NAME | FIRST_NAME
-: | :--- | :-------- | :---------
 1 | A    | Billy     | John      
 4 | C    | Billy     | John      
相关问题