我需要以最有效的方式获取薪水第三高的员工的所有细节。
我的查询:
select(SELECT MIN(Salary)
FROM (SELECT * TOP (3) Salary
FROM Employees
ORDER BY Salary)
我的查询中是否有任何问题。我可以更正我的查询。请帮助。
答案 0 :(得分:2)
使用RANK
; WITH T AS
(
SELECT * , RANK() OVER (ORDER BY SalaryDESC) as rk
FROM Employees
)
Select TOP(1) *
FROM T
WHERE T.rk=3
答案 1 :(得分:1)
你可以使用 Rownumber :这里我用empid分区以避免关系
;With cte
as
(
select *,row_number() over (partition by empid order by salary desc) as rownum
from
table
)
select * from cte where rownum=3
如果您想使用您的查询:
SELECT MIN(Salary
FROM (
SELECT TOP (3) Salary
FROM Employees
ORDER BY Salary
)b
答案 2 :(得分:1)
有几种方法可以做到这一点。
有两种可能的方法row_number
(或其他窗口函数,例如rank
或dense_rank
)top
,然后在结果集上使用我建议不使用row_number
,因为这需要更多的cpu,而是使用上述两种方法中的后者。
以下是两者的测试用例,显示的是子查询方法在不到四分之一的时间内运行。
create table #Salary (
PersonId int identity(1, 1) primary key clustered,
SalaryAmt decimal(16, 2) not null);
/* Insert some test data ... */
insert #Salary (
SalaryAmt)
select top (10000000)
abs(checksum(newid()) % 1000000)
from sys.all_columns a
cross join sys.all_columns b
set statistics io on;
set statistics time on;
select *
from (
select *,
RowNum = row_number() over (order by SalaryAmt desc)
from #Salary) a
where RowNum = 3;
set statistics time off;
set statistics io off;
checkpoint;
go
dbcc dropcleanbuffers;
go
set statistics io on;
set statistics time on;
select top 1 *
from (
select top 3 *
from #Salary
order by SalaryAmt desc) top_3
order by SalaryAmt;
set statistics time off;
set statistics io off;
结果如下:
SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 1 ms. PersonId SalaryAmt RowNum ----------- --------------------------------------- -------------------- 1427822 999999.00 3 Table '#Salary_____________________________________________________________________________________________________________000000000007'. Scan count 9, logical reads 27219, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 17123 ms, elapsed time = 2361 ms. DBCC execution completed. If DBCC printed error messages, contact your system administrator. SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 0 ms. PersonId SalaryAmt ----------- --------------------------------------- 1427822 999999.00 Table '#Salary_____________________________________________________________________________________________________________000000000007'. Scan count 9, logical reads 27219, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 4282 ms, elapsed time = 570 ms.
希望这有帮助。