SQL33 找出每个学校GPA最低的同学

知识点:group by 的坑

原题链接
描述
题目:现在运营想要找到每个学校gpa最低的同学来做调研,请你取出每个学校的最低gpa。

在这里插入图片描述

错误答案:

SELECT device_id,university,MIN(gpa)
FROM user_profile
GROUP BY university 
ORDER BY university 

这样写会报错:

“Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘user_profile.device_id’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by”

原因是违背了 only_full_group_by 原则,如果是自己做项目,那当然可以改一下 MySQL 的配置解决这个问题,但现在是做题,不能修改人家牛客的配置,所以这道题说白了就是不让你用这种方式解答

【group by 的坑】
使用group by之后select 语句中不能出现常数、聚合函数、聚合键以外的字段,device_id 就是 … 以外的字段,所以出错了


本题正确答案:

select
  device_id,
  university,
  gpa
from
  user_profile
where
  (university, gpa) in (
    select
      university,
      min(gpa)
    from
      user_profile
    group by
      university
  )
order by
  university

猜你喜欢

转载自blog.csdn.net/QinLaoDeMaChu/article/details/128144460
33
GPA
今日推荐