Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL ROW_NUMBER with INNER JOIN

I need to use ROW_NUMBER() in the following Query to return rows 5 to 10 of the result. Can anyone please show me what I need to do? I've been trying to no avail. If anyone can help I'd really appreciate it.

SELECT * 
FROM   villa_data 
       INNER JOIN villa_prices 
         ON villa_prices.starRating = villa_data.starRating 
WHERE  villa_data.capacity >= 3 
       AND villa_data.bedrooms >= 1 
       AND villa_prices.period = 'lowSeason' 
ORDER  BY villa_prices.price, 
          villa_data.bedrooms, 
          villa_data.capacity 
like image 615
Jason Eyebe Avatar asked Mar 17 '12 17:03

Jason Eyebe


People also ask

Does inner join increases number of rows?

An inner join repeats each matching row in TableB for each row in TableA. So if there are 4 rows in TableA, and 7 in TableB, the maximum rowcount is 28. Example at SQL Fiddle. Save this answer.

Can we use ROW_NUMBER without partition?

ROW_NUMBER() Function without Partition By clausePartition by clause is an optional part of Row_Number function and if you don't use it all the records of the result-set will be considered as a part of single record group or a single partition and then ranking functions are applied.

What is ROW_NUMBER () over partition by in SQL?

PARTITION BY It is an optional clause in the ROW_NUMBER function. It is a clause that divides the result set into partitions (groups of rows). The ROW_NUMBER() method is then applied to each partition, which assigns a separate rank number to each partition.

Can we use ROW_NUMBER in WHERE clause of SQL?

The ROW_NUMBER function cannot currently be used in a WHERE clause. Derby does not currently support ORDER BY in subqueries, so there is currently no way to guarantee the order of rows in the SELECT subquery.


1 Answers

You need to stick it in a table expression to filter on ROW_NUMBER. You won't be able to use * as it will complain about the column name starRating appearing more than once so will need to list out the required columns explicitly. This is better practice anyway.

WITH CTE AS
(
SELECT /*TODO: List column names*/
       ROW_NUMBER() 
          OVER (ORDER BY villa_prices.price, 
                         villa_data.bedrooms, 
                         villa_data.capacity) AS RN
FROM   villa_data 
       INNER JOIN villa_prices 
         ON villa_prices.starRating = villa_data.starRating 
WHERE  villa_data.capacity >= 3 
       AND villa_data.bedrooms >= 1 
       AND villa_prices.period = 'lowSeason' 

)
SELECT /*TODO: List column names*/
FROM CTE
WHERE RN BETWEEN 5 AND 10
ORDER BY RN
like image 55
Martin Smith Avatar answered Oct 01 '22 07:10

Martin Smith