所以我提供了这个代码来添加一个行列,但是,当我尝试按该行列进行过滤时,它会显示' Row'的无效列名。如果我删除底部的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
答案 0 :(得分:3)
由于正在进行逻辑查询处理,尝试引用WHERE
子句中的别名列不起作用。在WHERE
子句之前评估SELECT
。因此,在评估ROW
时,列WHERE
不存在。
在此示例中引用列的正确方法是:
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
答案 1 :(得分:2)
列'行'不属于子查询别名为' a'。此外,您无法使用别名' Row'因为SQL操作顺序而在where子句中。
我相信您可以将两个查询简化为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