Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting top( x ) multiple times

Sorry for the rubbish title but hopefully this will explain:

Given the table

 name     |   data
---------------------
   1      |   1000
   1      |   2000
   1      |   3000
   2      |   1500
   2      |   2500
   2      |   3500

I want to be able to select the top( x ) for all names ordered by the data value. So if x = 2 the return will be

 name     |   data
---------------------
   1      |   2000
   1      |   3000
   2      |   2500
   2      |   3500
like image 906
Patrick Avatar asked Dec 21 '22 22:12

Patrick


1 Answers

;with cte AS
(
SELECT name, data, ROW_NUMBER() OVER (PARTITION BY name ORDER BY data DESC) AS RN
FROM YourTable
)
SELECT name, data
FROM cte 
WHERE RN<=2
ORDER BY name, data
like image 192
Martin Smith Avatar answered Jan 06 '23 09:01

Martin Smith