As I know HAVING
clause is used to filter rows for each group.
I have a table that stores scores of students.
create table sc
(
`classid` int,
`studentid` int,
`score` int
);
Here is the sample data:
+---------+-----------+-------+
| classid | studentid | score |
+---------+-----------+-------+
| 1 | 1 | 50 |
| 1 | 2 | 59 |
| 1 | 3 | 80 |
| 1 | 4 | 68 |
| 1 | 5 | 70 |
| 1 | 6 | 20 |
| 1 | 7 | 90 |
| 1 | 8 | 100 |
| 1 | 9 | 25 |
| 2 | 1 | 51 |
| 2 | 2 | 59 |
| 2 | 3 | 80 |
| 2 | 4 | 68 |
| 2 | 5 | 70 |
| 2 | 6 | 30 |
| 2 | 7 | 44 |
| 2 | 8 | 80 |
| 3 | 1 | 20 |
| 1 | 11 | 30 |
| 1 | 12 | 40 |
+---------+-----------+-------+
And I want to query the max score of each class, so I wrote this SQL statement:
select *
from sc
group by classid
having score = max(score);
But the output is not what I expect. The output only prints one row.
+---------+-----------+-------+
| classid | studentid | score |
+---------+-----------+-------+
| 3 | 1 | 20 |
+---------+-----------+-------+