2017-08-25 81 views
0

所以我有這個代碼我想出來添加一個行列,但是,當我嘗試按行列過濾時,它說'無效的列名'行」。如果我刪除底部的WHERE子句,則代碼按預期運行。不知道我做錯了什麼。爲什麼我不能用WHERE子句過濾我的行列

SELECT 
    ROW_NUMBER() OVER(ORDER BY a.JobNo) AS [Row], 
    a.JobNo, 
    a.PartNo, 
    a.WorkCntr, 
    a.StepNo 
FROM 
    (SELECT DISTINCT TOP 1000 r.JobNo, 
          r.PartNo, 
          r.WorkCntr, 
          r.StepNo 
    FROM OrderRouting r 
    RIGHT JOIN Scheduling s ON r.JobNo = s.JobNo 
    WHERE r.WorkCntr = 'Z-Straight' 
    AND (r.Status = 'Current' OR r.Status = 'Pending' OR r.Status = 'Future') 
    AND r.JobNo NOT LIKE '10415%' 
    AND r.JobNo NOT LIKE '44444%' 
    AND r.JobNo NOT LIKE '77777%' 
    ORDER BY r.JobNo 
    ) a 
WHERE a.Row > 10 

回答

3

試圖引用WHERE子句中的別名列不起作用,因爲發生邏輯查詢處理。在SELECT子句之前評估WHERE。因此,當評估WHERE時,列ROW不存在。

在這個例子中,以引用列中的正確的方法是:

select * from (
    SELECT 
    ROW_NUMBER() OVER(ORDER BY a.JobNo) AS [Row], 
    a.JobNo, 
    a.PartNo, 
    a.WorkCntr, 
    a.StepNo 
    FROM 
    (
     SELECT DISTINCT 
     TOP 1000 
     r.JobNo, 
     r.PartNo, 
     r.WorkCntr, 
     r.StepNo 
     FROM OrderRouting r RIGHT JOIN Scheduling s ON r.JobNo = s.JobNo 
     WHERE r.WorkCntr = 'Z-Straight' 
     AND (r.Status = 'Current' 
     OR r.Status = 'Pending' 
     OR r.Status = 'Future') 
     AND r.JobNo NOT LIKE '10415%' 
     AND r.JobNo NOT LIKE '44444%' 
     AND r.JobNo NOT LIKE '77777%' 
     ORDER BY r.JobNo 
    ) a 
    )b 
    WHERE b.Row > 10 
+0

感謝您的解釋,你的代碼的偉大工程 –

+1

在大數據量的情況下,您的查詢將執行非常糟糕。 – SouXin

+0

@SouXin同意,不確定是否屬實。只專注於解釋爲什麼它不適用於OP – Horaciux

2

列「行」不是別名爲「A」的子查詢的一部分。此外,由於操作的SQL順序,您將無法在where子句中使用別名「Row」。

我相信你可以簡化你的兩個查詢到的CTE:

with cte as(
SELECT DISTINCT 
TOP 1000 
r.JobNo, 
r.PartNo, 
r.WorkCntr, 
r.StepNo, 
ROW_NUMBER() OVER(ORDER BY a.JobNo) AS [Row] 
FROM OrderRouting r 
RIGHT JOIN Scheduling s ON r.JobNo = s.JobNo 
WHERE r.WorkCntr = 'Z-Straight' 
    AND (r.Status IN('Current','Pending','Future') 
    AND r.JobNo NOT LIKE '10415%' 
    AND r.JobNo NOT LIKE '44444%' 
    AND r.JobNo NOT LIKE '77777%') 

SELECT * 
FROM cte 
WHERE Row > 10 
相關問題