这是一道面试题,今天有空把它记下来,以后遇到此类问题作个参考!刚一看到这个题目,估计好多人都会想到关键字top,其实这里用到的关键字是partition,
好了,先看看表结构,及数据吧!
接下来看一看partition的功能,执行语句
select c.*,ROW_NUMBER() over (partition by c.ID order by c.Sorce desc) rank from dbo.courcer c
结果如下:
到这里一目了然知道最终结果了!
View Code
select s.*,c.* from dbo.student s left join ( select c.*,ROW_NUMBER() over (partition by c.ID order by c.Sorce desc) rank from dbo.courcer c ) c on s.ID=c.ID where c.rank<=2