我正在使用其中包含子查询的CTE。然后我尝试从CTE中的子查询结果中进行选择,但我收到Invalid Column Name
错误。
查询:
DECLARE @User AS VARCHAR(50)
SET @User = 'test.user'
WITH cte AS (
SELECT
o.db_OrderNo,
o.db_Deferral
FROM
tblOrders o
LEFT JOIN tblUserProfile up on up.db_UserId = o.db_RTS
WHERE
o.db_Deleted = 0
AND (select OrderBucketId from Main.udfGetOrderStatusStepInfoByOrderNo(o.db_OrderNo) as Task) IN (1, 2, 3, 4)
AND up.db_Email LIKE @User + '%'
)
SELECT COUNT(DISTINCT (CASE WHEN Task = 1 AND db_Deferral = 0 THEN db_OrderNo
END)) as OrderInEvalCount,
COUNT(DISTINCT (CASE WHEN Task = 2 AND db_Deferral = 0 THEN db_OrderNo
END)) as OrderInDfcCount,
COUNT(DISTINCT (CASE WHEN Task IN (3, 4) AND (select OrderStepId from Main.udfGetOrderStatusStepInfoByOrderNo(o.db_OrderNo)) NOT IN (37, 39) AND
db_Deferral = 0 THEN db_OrderNo
END)) as OrderWipCount,
COUNT(DISTINCT (CASE WHEN db_Deferral <> 0 THEN db_OrderNo
END)) as OrderInPendedCount
FROM cte;
它没有将Task
识别为列。不习惯做子查询,因此格式可能是错误的。不确定临时表是否有帮助。任何帮助将不胜感激。
答案 0 :(得分:0)
您的子查询位于WHERE
子句中。列只来自FROM
子句。您可以通过多种方式处理此问题。如果您知道子查询不返回重复项,则使用FROM
将逻辑移至CROSS APPLY
子句:
WITH cte AS (
SELECT o.db_OrderNo, o.db_Deferral
FROM tblOrders o LEFT JOIN
tblUserProfile
up on up.db_UserId = o.db_RTS CROSS APPLY
Main.udfGetOrderStatusStepInfoByOrderNo(o.db_OrderNo) t
WHERE o.db_Deleted = 0 AND
t.OrderBucketId IN (1, 2, 3, 4) AND
up.db_Email LIKE @User + '%'
)