2012-03-17 183 views
3

我需要在下面的查詢中使用ROW_NUMBER()來返回結果的第5到10行。任何人都可以告訴我我需要做什麼?我一直在努力沒有用。如果有人可以幫助,我會非常感激。SQL ROW_NUMBER with INNER JOIN

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 
+1

這看起來有點家庭作業-y-你有什麼*嘗試*?它是否導致錯誤? 「錯」結果?你顯然*已經知道'ROW_NUMBER'是執行分頁的正確功能... – 2012-03-17 17:57:03

+0

@Damien_The_Unbeliever他提供了查詢。對不起,只是想要合理。這是一個有效的問題。 – 2012-09-27 12:41:18

回答

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 
+0

其實你可以使用*:[[SELECT ROW_NUMBER()OVER(ORDER BY ...)AS [RN],* FROM ...]] – Learner 2013-04-15 07:37:24

+0

...但是當然,不推薦使用*不推薦 – Learner 2013-04-15 07:51:43

+0

@ Cristi - 他們不能使用'*'的原因是因爲列名'starRating'出現在CTE中的兩個表和列名中必須是唯一的。 – 2013-04-15 08:14:51

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; 
+0

這一個帶回了結果。謝謝!我有一個問題...我可以從ASP執行此操作嗎?我已經嘗試添加到我的頁面代碼與標準的「oDatabase.SQL =」與t AS(SELECT ...「,但它不返回任何行,我是否錯過了什麼?如果這是一個愚蠢的問題,道歉 – 2012-03-17 18:24:32

+0

@JasonEyebe對不起,我根本不熟悉ASP。 – 2012-03-17 18:25:30