Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select top X from a Row_number in SQL Server ?

I have a data sample, and now i want to get data using TOP X combine ROW_NUMBER()

IndexNo ProductName
1       Black
2       Blue
3       Brown
4       Green
5       Red
6       White
7       Yellow

As follow in this case, i want to get the data, which after run SQL Statement, result as

IndexNo ProductName
3       Brown
4       Green
5       Red

I use this sql statement for this case, but i get this error Invalid column name 'IndexNo' , this is sql statement .

SELECT TOP 3  ROW_NUMBER() OVER(ORDER BY TEMPA.ProductName) AS IndexNo, TEMPA.ProductName  
FROM (
            SELECT DISTINCT ProductName FROM PRODUCTS WHERE ProductType ='Food'
) AS TEMPA
WHERE IndexNo  between 3 and 5
like image 377
Brian Crist Avatar asked Jan 26 '26 15:01

Brian Crist


1 Answers

You could use another level of subquery with parentheses.

SELECT TOP 3 * FROM
( SELECT ROW_NUMBER() OVER(ORDER BY TEMPA.ProductName) AS IndexNo, TEMPA.ProductName  
FROM (
            SELECT DISTINCT ProductName FROM PRODUCTS 
) AS TEMPA
  ) as TEMPB
WHERE IndexNo  between 3 and 5

DEMO

like image 169
Kaushik Nayak Avatar answered Jan 29 '26 08:01

Kaushik Nayak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!