首页 > 解决方案 > SQL 选择语句,其中一门课程多于另一门课程

问题描述

在此处输入图像描述

我想要的是返回名称 A,因为 A 是唯一一个英语成绩优于 Geo 的人。

基本问题是选择所有英语分数>地理分数的学生

标签: sql

解决方案


您可以使用group byand执行此操作having

select name
from t
where course in ('Eng', 'Geo')
group by name
having max(case when course = 'Eng' then score end) > max(case when course = 'Geo' then score end);

如果每个名称/课程只有一个分数,您还可以使用joins,例如:

select teng.name
from t teng join
     t tgeo
     on teng.name = tgeo.name and
        teng.course = 'Eng' and
        tgeo.course = 'Geo' and
        teng.score > tgeo.score;

推荐阅读