简体   繁体   English

SQL行比较查询

[英]SQL Row Comparison Query

I am new to SQL and trying to write a query against the following results table that would allow me to list the subjects where the student Mary has got a higher score than Tom. 我是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

The result should be a table as follows: 结果应为下表:

    Subject     
    ---------
    Maths
    Geography

I believe I should be using the join clause but am unable to get this to work. 我相信我应该使用join子句,但无法使其正常工作。

Thanks 谢谢

You can actually do this with aggregation, assuming there are no duplicate scores. 假设没有重复的分数,您实际上可以使用聚合来完成。

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);

Note that this will include subject where Mary has a score but Tom doesn't. 请注意,这将包括玛丽得分较高但汤姆没有得分的主题。

You can generalize this with a self-join as follows: 您可以使用自联接将其概括如下:

SQL Fiddle SQL小提琴

Query: 查询:

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 |

Then, obviously, you can filter the results by adding this WHERE clause. 然后,显然,您可以通过添加此WHERE子句来过滤结果。

where a.student ='Mary' AND b.student = 'Tom

This query would give you the desired result: 该查询将为您提供所需的结果:

SELECT subject
FROM   scores
WHERE  student = 'Mary'
AND    ( subject
       , score
       ) IN (
            SELECT   subject
            ,        MAX( score )
            FROM     scores
            GROUP BY subject
            );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM