想象一下下表:
result_id student subject grade
1 Anne A 63
2 Anne B 63
3 Bob A 89
4 Bob B 51
5 Carla A 70
6 Carla B 70
7 Carla C 68
8 Dylan B 75
9 Dylan C 54
我想回傳學生在科目 A 和 B 上獲得完全相同成績的條目。所以理想的輸出是:
result_id student subject grade
1 Anne A 63
2 Anne B 63
5 Carla A 70
6 Carla B 70
這甚至可以通過查詢來實作嗎?努力尋找有關它的資訊。
uj5u.com熱心網友回復:
有點復雜,但我希望易于閱讀。
select * from the_table
where student in
(
with t as
(
select student, count(*) cnt, min(grade) mig, max(grade) mag
from the_table
where subject in ('A', 'B') group by student
)
select student from t where mig = mag and cnt = 2
)
and subject in ('A', 'B')
order by student, subject;
| result_id | 學生 | 主題 | 年級 |
|---|---|---|---|
| 1 | 安妮 | 一種 | 63 |
| 2 | 安妮 | 乙 | 63 |
| 5 | 卡拉 | 一種 | 70 |
| 6 | 卡拉 | 乙 | 70 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/448965.html
標籤:sql PostgreSQL 子查询
下一篇:如何從字串中動態提取子字串?
