我是SQL新手并试图针对以下结果表编写查询,这样我就可以列出学生Mary得分高于Tom的科目。
Subject Student Teacher Score
--------------------------------------------------
Maths Tom Anderson 67
Maths Mary Anderson 68
English Tom Lewis 55
English Mary Lewis 44
French Tom Joubert 87
French Mary Joubert 76
Geography Tom Arnold 76
Geography Mary Arnold 82
结果应该是一个表格如下:
Subject
---------
Maths
Geography
我相信我应该使用join子句但是无法使用它。
由于
答案 0 :(得分:2)
假设没有重复的分数,您实际上可以通过聚合执行此操作。
select subject
from results
group by subject
having max(case when student = 'Mary' then score end) >
max(case when student = 'Tom' then score else 0 end);
请注意,这将包括Mary有分数但Tom没有的主题。
答案 1 :(得分:0)
您可以使用自连接对此进行概括,如下所示:
查询:
select a.Student As higher, b.Student as lower, a.Subject
from score a
join score b ON a.Student <> b.Student
AND a.Subject = b.Subject
AND a.Score > b.Score
<强> Results 强>:
| HIGHER | LOWER | SUBJECT |
|--------|-------|-----------|
| Mary | Tom | Maths |
| Tom | Mary | English |
| Tom | Mary | French |
| Mary | Tom | Geography |
然后,显然,您可以通过添加此WHERE
子句来过滤结果。
where a.student ='Mary' AND b.student = 'Tom
答案 2 :(得分:0)
此查询将为您提供所需的结果:
SELECT subject
FROM scores
WHERE student = 'Mary'
AND ( subject
, score
) IN (
SELECT subject
, MAX( score )
FROM scores
GROUP BY subject
);