加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

SQL查询 按某一字段分组,组内排序,取前n条数据

(2012-04-25 17:41:52)
标签:

获取前n条数据

分组

排序

查询

杂谈

表名ss 字段名id,time
数据:
 id  time
 1  2:20
 1  2:30
 1  2:40
 2  2:20
 2  2:20
 2  2:40

查询:

select * from ss a
 where 2>(select count(id) from ss b where a.time <b.time  and a.id=b.id)

结果:
 id  time
 1  2:20
 1  2:30
 2  2:20
 2  2:30

select * 
from
 (select id,time,(select count(*) 
        from ss
        where id = a.id and time<=a.time
        ) as arrcount 
 from ss as a
 ) as b 
where
b.arrcount<=2

题目:

S表(Sid,Sname)为学生表,C(Cid,Cname,Cteacher)为课程表,SC(Sid,Cid,Scgrade)为选课关系表。其中,Sid为学号,Sname为姓名,Cid为课程号,Cname为课程名,Cteacher为任课教师,Scgrade为学生成绩。 请用SQL语言实现: 列出每门课程成绩最好的两位学生的课程名称,姓名,成绩。

-----------------------------方法一
select * from
(select * from
 sc as a where (select Count(*) from sc as b where a.cid=b.cid and b.scgrade>=a.scgrade) <=2 ) as aa,s,c where s.sid=aa.sid and c.cid =aa.cid order by aa.cid

-----------------------------方法二
select * from
(select *,(select count(*) from sc as b where a.cid = b.cid and b.scgrade >= a.scgrade) as counts from sc  as a  ) as a1,s as a2,c as a3 where a1.sid=a2.sid and a1.cid=a3.cid and a1.counts<=2 order by a1.cid


0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有