带有INNER JOIN的SQL ROW_NUMBER

时间:2012-03-17 17:53:37

标签: sql sql-server row-number

我需要在以下Query中使用ROW_NUMBER()来返回结果的第5到10行。谁能告诉我我需要做什么?我一直试图无济于事。如果有人可以提供帮助,我会非常感激。

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 

2 个答案:

答案 0 :(得分:10)

您需要将其粘贴在表格表达式中以过滤ROW_NUMBER。您将无法使用*,因为它会抱怨列名starRating出现多次,因此需要明确列出所需的列。无论如何,这是更好的做法。

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

答案 1 :(得分:0)

您可以使用with子句。请尝试以下

WITH t AS
(
SELECT villa_data.starRating, 
   villa_data.capacity,
   villa_data.bedrooms,
   villa_prices.period,
   villa_prices.price,
   ROW_NUMBER() OVER (ORDER BY villa_prices.price, 
      villa_data.bedrooms, 
      villa_data.capacity ) AS 'RowNumber'
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 * 
FROM t 
WHERE RowNumber BETWEEN 5 AND 10;