0

我是 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 子句,但无法使其正常工作。

谢谢

4

3 回答 3

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 没有分数的主题。

于 2015-01-17T19:25:54.597 回答
0

您可以使用自联接来概括这一点,如下所示:

SQL小提琴

询问:

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

结果

| HIGHER | LOWER |   SUBJECT |
|--------|-------|-----------|
|   Mary |   Tom |     Maths |
|    Tom |  Mary |   English |
|    Tom |  Mary |    French |
|   Mary |   Tom | Geography |

然后,显然,您可以通过添加此WHERE子句来过滤结果。

where a.student ='Mary' AND b.student = 'Tom
于 2015-01-17T19:31:23.463 回答
0

此查询将为您提供所需的结果:

SELECT subject
FROM   scores
WHERE  student = 'Mary'
AND    ( subject
       , score
       ) IN (
            SELECT   subject
            ,        MAX( score )
            FROM     scores
            GROUP BY subject
            );
于 2015-01-17T21:54:52.013 回答