mysql 分组取前N记录
2016-05-19 11:37
597 查看
要求取出各班前两名(允许并列第二)
create table Table1 (id int auto_increment primary key, SName varchar(50),ClsNo varchar(20), Score int(3));
insert into Table1(SName,ClsNo,Score) values('AAAA','C1',67),('BBBB','C1',55);
insert into Table1(SName,ClsNo,Score) values('CCCC','C1',67),('DDDD','C1',65)('EEEE','C1',95);
insert into Table1(SName,ClsNo,Score) values('FFFF','C2',57),('GGGG','C2',87),('HHHH','C2',74);
insert into Table1(SName,ClsNo,Score) values('IIII','C2',52),('JJJJ','C2',81),('KKKK','C2',67);
insert into Table1(SName,ClsNo,Score) values('LLL','C2',66);
要求取出各班前两名(允许并列第二)
select *
from Table1 a
where 2>(select count(*) from Table1 where ClsNo=a.ClsNo and Score>a.Score)
order by a.ClsNo,a.Score desc
或者
select *
from Table1 a
where id in (select id from Table1 where ClsNo=a.ClsNo order by Score desc
limit 2)
order by a.ClsNo,a.Score desc
特例 N=1 ,即取最大的/最小的一条记录。
select
*
from Table1 a
where not exists (select 1 from Table1 where ClsNo=a.ClsNo and Score>a.Score);
select *
from (select * from Table1 order by Score desc) t
group by ClsNo
create table Table1 (id int auto_increment primary key, SName varchar(50),ClsNo varchar(20), Score int(3));
insert into Table1(SName,ClsNo,Score) values('AAAA','C1',67),('BBBB','C1',55);
insert into Table1(SName,ClsNo,Score) values('CCCC','C1',67),('DDDD','C1',65)('EEEE','C1',95);
insert into Table1(SName,ClsNo,Score) values('FFFF','C2',57),('GGGG','C2',87),('HHHH','C2',74);
insert into Table1(SName,ClsNo,Score) values('IIII','C2',52),('JJJJ','C2',81),('KKKK','C2',67);
insert into Table1(SName,ClsNo,Score) values('LLL','C2',66);
要求取出各班前两名(允许并列第二)
select *
from Table1 a
where 2>(select count(*) from Table1 where ClsNo=a.ClsNo and Score>a.Score)
order by a.ClsNo,a.Score desc
或者
select *
from Table1 a
where id in (select id from Table1 where ClsNo=a.ClsNo order by Score desc
limit 2)
order by a.ClsNo,a.Score desc
特例 N=1 ,即取最大的/最小的一条记录。
select
*
from Table1 a
where not exists (select 1 from Table1 where ClsNo=a.ClsNo and Score>a.Score);
select *
from (select * from Table1 order by Score desc) t
group by ClsNo
相关文章推荐
- mac mysql error You must reset your password using ALTER USER statement before executing this statem
- mysql分表的三种方法
- [mysql]数据库复习
- mysql 语句执行顺序
- MySQL 创建自定义函数
- mysqldump的实现原理
- mysql 删除重复数据
- mysql索引总结----mysql 索引类型以及创建
- 彻底卸载mysql
- python2代码中的mysqldb转python3 用pymysql
- 转载---Mysql常用命令详解
- mysql出现innodb缺失错误 #1286
- mysql 主从同步故障解决 Error 'Row size too large (> 8126).
- Mysql主从配置,实现读写分离
- 让MySql支持Emoji表情存储
- 更改在 Ubuntu 的 Mysql 密碼
- mysql in 子查询 效率慢 优化(转)
- mysql按字段根据某条件去重 nohup挂后台无法输出日志 系统时间查询 2016.05.18回顾
- mysql索引学习
- mysql配置文件