2017-09-27 90 views
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 #t 

預期輸出:希望第二高的薪水,以便通過部門明智

id   deptid sal 
2    1    2000 
5    2    3000 
+1

等都不是代碼寫作服務。你有什麼嘗試,你卡在哪裏? – HoneyBadger

回答

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 
0
;WITH CTE 
AS 
(
    SELECT ID, deptid, sal, ROW_NUMBER() OVER(PARTITION BY deptid ORDER BY deptid) SR FROM #t 
) 

SELECT ID, deptid, sal FROM CTE WHERE SR = 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