Sql-server – Find 13th min value in table group by a column

sql server

I am trying to replicate Small function in Excel which is Small(Array,K) gives Kth smallest element from stream of data.

I want to find 13th Min value for perticular Column values. in my table I have 2 columns A and B for each A column row value I have lets say 20 B values. I am trying to find 13th Smallest value for Each A value from column B

I am using following query to get min from group by clause

select A,min(B) from test group by Level_Name

I want to find 13th smallest value and not the smallest value.

I added tried a new query as

with a as(
select A,B,ROW_NUMBER() over (order by A,B) as rownum 
 from test 
group by Level_Name,pl
)
select A,B from a 
where rownum=13
group by A,B

It is returning only 13th number for 1 of the A value but there are multiple rows in A.

Best Answer

A quick solution would be to use Row_Number and select for the row number you are interested in. Something like:

--demo setup
Declare @Table table (ColA int, ColB int);
insert into @Table(ColA,ColB) values
(1,10),
(1,20),
(1,30),
(1,40),
(1,50),
(1,60),
(1,70),
(1,80),
(1,90),
(1,100),
(1,110),
(1,120),
(1,130),
(1,140),
(1,150),
(1,160),
(1,170),
(1,180),
(1,190),
(1,200),

(2,10),
(2,20),
(2,30),
(2,40),
(2,50),
(2,60),
(2,70),
(2,80),
(2,90),
(2,100),
(2,110),
(2,120),
(2,130),
(2,140),
(2,150),
(2,160),
(2,170),
(2,180),
(2,190),
(2,200);

--solution
select * from 
(
select *,ROW_NUMBER() over(partition by ColA order by ColB) as rn
from @Table
) a
where rn = 13;  --The row number you are interested in.

| ColA | ColB | rn |
|------|------|----|
| 1    | 130  | 13 |
| 2    | 130  | 13 |