分组topN

数据库表结构:sc

sid:学生id

cid:课程id

socre:分数

需求:查询每门课程分数最高的三个学生

select a.* from sc a where 3 > (select count(*) from sc where a.cid=cid and a.socre>score)

order by a.cid,a.score desc

分析:利用子查询建立一个笛卡尔积,对于a表的每一行都跟另外一个表的每一行匹配,如果count的值小于N说明该行的分数在top N之内

select a.* from sc a left join sc b on a.cid=b.cid and a.score>b.score group by a.sid,a.cid,a.score having count(*) <= 3 order by a.gid,a.score desc

猜你喜欢

转载自lishichang.iteye.com/blog/2231310