PostgreSQL:Return 个基于条件和分组的条目
PostgreSQL: Return entries based on conditions and grouping
想象一下 table:
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
我想要 return 学生在科目 A 和 B 中获得完全相同成绩的条目。因此理想的输出是:
result_id student subject grade
1 Anne A 63
2 Anne B 63
5 Carla A 70
6 Carla B 70
这甚至可以通过查询来实现吗?正在努力寻找有关它的信息。
有点复杂,但我希望容易阅读。
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
student
subject
grade
1
Anne
A
63
2
Anne
B
63
5
Carla
A
70
6
Carla
B
70
想象一下 table:
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
我想要 return 学生在科目 A 和 B 中获得完全相同成绩的条目。因此理想的输出是:
result_id student subject grade
1 Anne A 63
2 Anne B 63
5 Carla A 70
6 Carla B 70
这甚至可以通过查询来实现吗?正在努力寻找有关它的信息。
有点复杂,但我希望容易阅读。
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 | student | subject | grade |
---|---|---|---|
1 | Anne | A | 63 |
2 | Anne | B | 63 |
5 | Carla | A | 70 |
6 | Carla | B | 70 |