sql分组后获取top
2016-03-17 00:00
627 查看
数据库表字段name,course,score分别为姓名,学科,分数;需求:查询出每个学科的前5名
//建表start
create table t_student(
name String,
course String,
score int
)
row format delimited
fields terminated by '\t'
stored as textfile;
//建表end
//产生测试数据start
public void test1() throws Exception{
String[] names=new String[100];
String[] course=new String[]{"数学","语文","英语","政治","地理","高数","计算机","会计"};
File file=new File("E:/score.txt");
FileWriter fw=new FileWriter(file);
Random rand = new Random();
for(int i=0;i<names.length;i++){
names[i]="name"+i;
}
for(int i=0;i<names.length;i++){
for(int j=0;j<course.length;j++){
String s=names[i]+"\t"+course[j]+"\t"+rand.nextInt(101)+"\n";
//System.out.printf(s);
fw.write(s);
}
}
fw.close();
}
//产生测试数据end
select * from (select *,row_number() over(partition by course order by score desc) as rownum from t_student) t where rownum<=5;
其中select *,row_number() over(partition by course order by score desc) as rownum from t_student按学科进行了分组,按成绩进行了降序,获取了每一组的行号
外层的查询对每一组的行号取top,得到最终结果:
//建表start
create table t_student(
name String,
course String,
score int
)
row format delimited
fields terminated by '\t'
stored as textfile;
//建表end
//产生测试数据start
public void test1() throws Exception{
String[] names=new String[100];
String[] course=new String[]{"数学","语文","英语","政治","地理","高数","计算机","会计"};
File file=new File("E:/score.txt");
FileWriter fw=new FileWriter(file);
Random rand = new Random();
for(int i=0;i<names.length;i++){
names[i]="name"+i;
}
for(int i=0;i<names.length;i++){
for(int j=0;j<course.length;j++){
String s=names[i]+"\t"+course[j]+"\t"+rand.nextInt(101)+"\n";
//System.out.printf(s);
fw.write(s);
}
}
fw.close();
}
//产生测试数据end
select * from (select *,row_number() over(partition by course order by score desc) as rownum from t_student) t where rownum<=5;
其中select *,row_number() over(partition by course order by score desc) as rownum from t_student按学科进行了分组,按成绩进行了降序,获取了每一组的行号
外层的查询对每一组的行号取top,得到最终结果:
相关文章推荐
- Hegemon:使用 Rust 编写的模块化系统监视程序
- mysql 前几条记录语句之(limit)
- top、clientTop、scrollTop、offsetTop
- 使用 TOP 子句限制UPDATE 语句更新的数据
- asp中 select top 问题!~
- 关于js中window.location.href,location.href,parent.location.href,top.location.href的用法与区别
- js中top的作用深入剖析
- JS window对象的top、parent、opener含义介绍
- js中不同的height, top的区别对比
- Linux Top 命令解析
- 国外正流行的不常见Linux发行版简介
- linux top命令查看内存及多核CPU的使用讲述 [转]
- mssql server利用top分页
- linux命令之top该怎么用?top命令详解
- htop,dstat,top,ps命令的使用
- Linux top 命令详解
- linux top命令详解
- Linux 指令篇:工作行程资讯与管理--top
- top 显示CPU所有核心信息
- linux top进程状态D