请考虑以下表格: -
-----------------------------------------
ID TEACHER SUBJECT GRADE
-----------------------------------------
1 Jack Physics 8
2 Paul Chemistry 10
3 Susan English 6
4 Jack Maths 8
5 Jack Physics 10
6 Paul Chemistry 10
我想识别TEACHER和SUBJECT列具有相同值的行。与ID和GRADE列中的值无关。因此将识别以下行: -
-------------------------------------
ID TEACHER SUBJECT GRADE
-------------------------------------
1 Jack Physics 8
2 Paul Chemistry 10
5 Jack Physics 10
6 Paul Chemistry 10
-------------------------------------
如何在oracle sql中实现这样的结果。
答案 0 :(得分:1)
您可以使用以下选择:
SELECT
a.*
FROM (SELECT
COUNT(1) cnt,
teacher,
subject
FROM your_table
GROUP BY teacher,subject
HAVING COUNT(1) > 1)rec,
Your_table a
WHERE a.teacher=rec.teacher AND a.subject=rec.subject
答案 1 :(得分:0)
SELECT * FROM table1 t1
WHERE EXISTS (
SELECT null FROM Table1 t2
WHERE t1."TEACHER" = t2."TEACHER"
AND t1."SUBJECT" = t2."SUBJECT"
AND t1."ID" <> t2."ID"
)
ORDER BY "ID"
答案 2 :(得分:0)
使用ROW_NUMBER()
将为教师和主题的独特组合提供一种简单的方法来选择一行,但我还没有完全匹配问题提供的结果。但是,使用ROW_NUMBER()
启用一个逻辑,您可以在其中选择哪个(哪些)字段将确定返回哪些行:
SELECT
id, teacher, subject, grade
FROM (
SELECT
id, teacher, subject, grade
, row_number() over(partition by teacher, subject ORDER BY id ASC) as RN
FROM Table1
)
WHERE rn = 1
ORDER BY teacher, subject ;
使用ID的升序结果为:
| ID | TEACHER | SUBJECT | GRADE |
|----|---------|-----------|-------|
| 4 | Jack | Maths | 8 |
| 1 | Jack | Physics | 8 |
| 2 | Paul | Chemistry | 10 |
| 3 | Susan | English | 6 |
或简单地将订单更改为:成绩DESC
| ID | TEACHER | SUBJECT | GRADE |
|----|---------|-----------|-------|
| 4 | Jack | Maths | 8 |
| 5 | Jack | Physics | 10 |
| 2 | Paul | Chemistry | 10 |
| 3 | Susan | English | 6 |
这种技术通常用于获取most recent
或oldest
行(基于某些日期/时间数据),以获取如何使用它的另一个示例。