0

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.

    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.

Thanks

fishboy76
  • 11
  • 1

3 Answers3

2

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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You can generalize this with a self-join as follows:

SQL Fiddle

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 a.student ='Mary' AND b.student = 'Tom
O. Jones
  • 103,626
  • 17
  • 118
  • 172
0

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
            );
mosaic
  • 11
  • 1