想要部门明智的第二高工资单

时间:2017-09-27 09:36:45

标签: sql sql-server sql-server-2008

create table #t 
(id int,
deptid int,
sal int)

insert into #t values (1,1,1000),(2,1,2000),(3,1,3000),(4,2,2000),(5,2,3000),(6,2,6000)

SELECT * FROM #t

预期产出:

id            deptid   sal
2              1              2000
5              2              3000

3 个答案:

答案 0 :(得分:1)

;with cte as
(select *, row_number() over(partition by deptid order by sal desc) as rn
from #t)

select *
from cte
where rn = 2

答案 1 :(得分:0)

<script>
    $('#editor').wysiwyg();
</script>

答案 2 :(得分:0)

您需要的查询

create table #t 
(id int,
deptid int,
sal int)

insert into #t values (1,1,1000),(2,1,2000),(3,1,3000),(4,2,2000),(5,2,3000),(6,2,6000)

select * from (
SELECT id,deptid,sal,row_number() over(partition by deptid order by sal)rnum FROM #t
) as a
where rnum=2