假设我们有一个方案表
student(id (primary key), name, math_score, english_score)
我正在尝试获得排名最高的学生信息(ID和姓名)(按数学分数和英语分数的最高总和排序)。可能有几个学生打领带,我们想要所有这些。我想这样做的方法是使用子查询来获得一个包含总和的表,然后找到具有最高总和的id,名称。
SELECT s.id, s.name
FROM (SELECT s.id, s.name, s.math_score+s.english_score as sum
FROM student s) s
WHERE s.sum = (SELECT max(s.sum)
FROM (SELECT s.id, s.name, s.math_score+s.english_score as sum
FROM student s) s)
这有效,但似乎非常多余且效率不高。
我刚开始学习sql语言,我很欣赏这个问题的一些见解!
答案 0 :(得分:1)
使用WITH TIES
create table #student(
id int primary key identity(1,1),
name varchar(50),
math_score decimal,
english_score decimal
)
insert into #student
values
('Tom', 90, 90),
('Dick', 70, 70),
('Harry', 80, 100)
select TOP(1) WITH TIES
id,
name,
math_score,
english_score,
math_score + english_score as ScoreRank
from #student
order by
math_score + english_score desc
给出答案:
id|name|math_score|english_score|ScoreRank
1|Tom|90|90|180
3|Harry|80|100|180
答案 1 :(得分:1)
这应该完成它,你在不必要的步骤中添加。
select id,
name,
math_score+english_score as total_score
from student
where math_score+english_score=(select max(math_score+english_score)
from student)
答案 2 :(得分:-1)
SELECT id, name, math_score+english_score as 'sum'
FROM student
Order by math_score+english_score DESC;