Sei sulla pagina 1di 2

Select nth largest value in a Table (SQL Server) Explained A (t1) A sal sal #00 200 $00 #00

200 $00

For the largest value there should be no value in the table which is greater than returned value, so (count(*) from A as t1 where sal > t1.sal) should return 0 So for largest value we select the value for which count(*) from A as t1 where sal > t1.sal returns 0 Or select sal from A t1 where 1-1 = (select count(*) from A where sal >
t1.sal)

For second largest value there should be only one value which is greater than the returned value. (So there should be n-1 distinct values which are greater than the nth largest value.) 200 is the value for which there is only one distinct value which is greater than 200. So for second largest value
select sal from A t1 where 2-1 = (select count(*) from A where sal > t1.sal)

This works fine when there are distinct values in the colu n! (1""#$""#%""& etc)
--*************************************************************************

For repeated values in the column Nth Largest value can be found using
select top 1 sal from (select *, dense_rank() over (order where rnk = n ! sal desc) as rnk from A)tmp

! (sal) #00 #00 200 200 $00

sal %"" $"" $"" 1"" 1""

rn" 1 $ $ % %

Potrebbero piacerti anche