表格score
字段名称 | 数据类型 |
ID | INT |
StudentClass | CHAR(255) |
Subject | CHAR(255) |
StudentName | CHAR(255) |
Score | INT |
表格内容e.g:
1.总分最高者
//方法1:按照总分降序排列,然后只选择第一行
select top 1 StudentClass,id,StudentName,sum(Score)
from score
group by id,StudentName,StudentClass
order by sum(Score) desc;
tip: top 1子句含义为查询结果只显示首条记录, group by 有一个原则,就是 select 后面的所有列中,没有使用聚合函数的列,必须出现在 group by 后面, 聚集函数只能用于select子句和group by 中的having子句。where 子句作用于基本表或视图,从中选择满足条件的元组,having 短语作用于组,从中选择满足条件的组。
//方法二:嵌套查询,将所有总分作为子查询,再用>=all(...),选择最终结果
select StudentClass,id,StudentName,sum(Score)
from score
group by id, StudentName,StudentClass
having sum(Score)>=all(select sum(Score)
from score group by id);
注意:子查询的select语句不能使用order by子句,order by子句只能对最终的结果进行排序。
2.某一科成绩最高者
select StudentClass, id, StudentName, Score
from score
where score =(select max(Score)
from score
where Subject = '科目的名称');
3.成绩排行榜
//方法一:基于派生表的查询
select distinct StudentClass, score.id,StudentName,sumsc
from score, (select id, sum(Score) as sumsc from score group by id order by sum(Score)desc) as sc1
where score.id = sc1.id
order by sumsc desc;
//可能这个会有bug,在数据库查询到的结果和用java查的结果不一样
select StudentClass,id,StudentName,sum(Score)
from score
group by id,StudentName,StudentClass
order by sum(Score) desc;
tip:为某一列重命名,<表名>.列名 as 重命名的名称。