Sunday, 1 January 2012

Find n-th element with t-sql

Here are few methods to get n-th element from a result set (or a table).
1) using sub query
--http://www.sqlteam.com/article/find-nth-maximum-value-in-sql-server

 use master
 go
 with T as
 (
 select
   number
   ,low
   ,high
   ,status
   from master..spt_values
   where type='P'
 )

 select
  *
  from T as A
  where 4=(select count(distinct B.number) from T as B where B.number<A.number)
 go
2) for sql server 2005 and above, rely on row_number function
 use master
 go
 with T as
 (
 select
   number
   ,ROW_NUMBER() over(order by number) as NumberOrder
   ,DENSE_RANK() over(order by number) as NumberRank
   ,low
   ,high
   ,status
   from master..spt_values
   where type='P'
 )
 --select * from T
 --select top 1 * from (select top 5 * from T order by number) X order by number desc
 select
  *
  from T
  where NumberOrder=5
  --where NumberRank=5
 go
3) double flip:
-- first part is identical
--select * from T
--select top 1 * from (select top 5 * from T order by number) X order by number desc

No comments:

Post a Comment