2014-11-06 50 views
1

我能夠在SQL執行以下操作:SQL - 排序OVER子句中

SELECT ROW_NUMBER() OVER (ORDER BY c.SomeField2 ASC) AS r, c.cID 
FROM 
(
    SELECT c.SomeField1, c.SomeField2, c.SomeField3, t.SomeField1Text, p.SomeField2Text 
    FROM MyTable c 
    JOIN #TempTable1 t ON c.SomeField1 = t.SomeField1 
    JOIN #TempTable2 p ON c.SomeField2 = p.SomeField2 
) c 

然而,當我嘗試從像這樣我的臨時表的一個列排序...

SELECT ROW_NUMBER() OVER (ORDER BY p.SomeField2Text ASC) AS r, c.cID 
FROM 
(
    SELECT c.SomeField1, c.SomeField2, c.SomeField3, t.SomeField1Text, p.SomeField2Text 
    FROM MyTable c 
    JOIN #TempTable1 t ON c.SomeField1 = t.SomeField1 
    JOIN #TempTable2 p ON c.SomeField2 = p.SomeField2 
) c 

...我收到以下錯誤:

The multi-part identifier "p.SomeFieldText2" could not be bound. 

你知道爲什麼我得到這個錯誤?我很困惑,因爲該專欄在我的SELECT條款中。

+0

我編輯了類型o在我的問題。我仍然有同樣的問題。 – WEFX 2014-11-06 16:05:47

+1

你有沒有嘗試'ORDER BY c.SomeField2Text ASC'? – 2014-11-06 16:16:37

+0

謝謝@ user2315555,我剛剛在看到Almazini的回答後試過。 – WEFX 2014-11-06 16:20:28

回答

0

你應該考慮你的子查詢像別名C.表

這就是爲什麼你需要c.SomeField2訂購列

SELECT ROW_NUMBER() OVER (ORDER BY c.SomeFieldText ASC) AS r, c.cID 
FROM 
(
    SELECT c.SomeField1, c.SomeField2, c.SomeField3, t.SomeField1Text, p.SomeField2Text, p.SomeField2 
    FROM MyTable c 
    JOIN #TempTable1 t ON c.SomeField1 = t.SomeField1 
    JOIN #TempTable2 p ON c.SomeField2 = p.SomeField2 
) c 
+0

那麼如何在SomeField2Text上排序呢?我不想排序SomeField2,因爲這實際上只是一個ID。我想對相應的文本值進行排序。 – WEFX 2014-11-06 16:08:02

+0

明白了...我可以使用c.SomeField2Text,因爲c是我的子查詢表名稱。謝謝(我在你的答案中編輯了代碼,但你的解釋是有道理的) – WEFX 2014-11-06 16:17:58

1

要查詢被稱爲SomeField2Text領域,不SomeFieldText2

SELECT ROW_NUMBER() OVER (ORDER BY p.SomeField2Text ASC) AS r, c.cID 
FROM 
(
    SELECT c.SomeField1, c.SomeField2, c.SomeField3, t.SomeField1Text, p.SomeField2Text 
    FROM MyTable c 
    JOIN #TempTable1 t ON c.SomeField1 = t.SomeField1 
    JOIN #TempTable2 p ON c.SomeField2 = p.SomeField2 
) c 
+0

我在我的問題中編輯了o型。我仍然有同樣的問題。 – WEFX 2014-11-06 16:06:34