select所有学生各学科组最高分的城市数据

select the data of all the students scoring highest marks in each subject group by city

我正在使用 mysql 版本 8.0.23

给定的 table 是:-

+-----+--------+-----------+-------+-----------|
| id  | name   | subject   | marks | city      |
+-----+--------+-----------+-------+-----------|
| 101 | ravi   | maths     |    70 | Mumbai    |
| 103 | Viaan  | english   |    26 | Bangalore |
| 104 | varun  | chemistry |    95 | delhi     |
| 105 | rishab | biology   |    69 | delhi     |
|  108| Mihika | maths     |    78 | Kolkata   |
|  110| Ishaan | english   |    39 | Bangalore |
+-----+--------+-----------+-------+-----------|

我想获取每个城市每个学科最高分学生的完整数据

select subject, city, max(marks) as highest
from students
group by subject, city
order by subject, city;

--

select subject
     , city
     , max(marks) as highest 
  from students 
 group 
    by subject
     , city 
 order 
    by subject
     , city;

+-----------+-----------+---------+
| subject   | city      | highest |
+-----------+-----------+---------+
| biology   | Bangalore |      87 |
| biology   | Chennai   |      58 |
| biology   | delhi     |      82 |
| biology   | Jaipur    |      52 |
| biology   | Kolkata   |      92 |
| biology   | Lucknow   |      98 |
| chemistry | Bangalore |      84 |
| chemistry | Chennai   |      64 |
| chemistry | delhi     |      95 |
| chemistry | Jaipur    |      83 |
| chemistry | Kolkata   |      45 |
| chemistry | Lucknow   |     100 |
| chemistry | Mumbai    |      87 |

我用过这个但是我还是看不到那个学生的名字和ID

这是使用 window 函数的一种方法:

select * from 
   ( 
    select * , rank() over (partition by subject, city order by mark desc) rn
    from yourtable
   ) t
where rn = 1
    select s.* from students s, (select subject, city, max(marks) as highest from students as b group by subject, city  order by subject, city) b where (s.city=b.city and s.subject=b.subject and s.marks=b.highest) order by city,subject; 

我使用了上面的查询这也给出了答案