SQL查询

表格score

字段名称

数据类型

IDINT
StudentClassCHAR(255)
SubjectCHAR(255)
StudentNameCHAR(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 重命名的名称。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值