------已解决--------
我不必尝试在CTE范围内执行减法,而只需将其放入主查询列表中使用此特定CTE的子查询中。
问题是,`InnerOQLI.FreePlaceCount未被识别,因为它尚未在CTE范围内定义,仅在Exists语句中使用。
------问题----------
这是我第一次使用CTE,我加入了多个CTE,这样我就可以在一列中检索总数。
我需要在其中一个CTE中执行减法
我第一次写这个
MyCount2
AS
(
SELECT DISTINCT
O.ID AS OrderID,
(
(
(SELECT SUM(InnerOC.[Count])
FROM Order InnerO
INNER JOIN SubOrder InnerSO ON InnerO.ID = InnerSO.OrderID
INNER JOIN OrderComponent InnerOC ON SO.ID = OC.SubOrderID
WHERE OC.OrderComponentTypeID IN (1,2,4,5)
AND EXISTS (SELECT * FROM OrderQuoteLineItem InnerOQLI
WHERE InnerOQLI.OrderQuoteLineItemTypeID = 9 AND Order.ID = InnerO.ID)
AND Inner0.ID = ).ID)
)
- --< Minus Here
OQLI.FreePlaceCount
) AS [SHPCommExpression2]
FROM Order O
INNER JOIN SubOrder SO ON O.ID = SO.OrderID
INNER JOIN OrderComponent OC ON SO.ID = OC.SubOrderID
INNER JOIN OrderQuoteLineItem OQLI ON SO.ID = 0QLI.SubOrderID
),
由于主查询中重复的行,由于没有详细说明,这会带回不正确的数据。 (我相信它是主要查询中相同连接的cos)
所以我写了这个
MyCount2
AS
(SELECT InnerO.ID AS OrderID
SUM(InnerOC.[Count]
- InnerOQLI.FreePlaceCount) --- Tried to place subtraction here ----
AS [SHPCommExpression12])
FROM Order InnerO
INNER JOIN SubOrder InnerSO ON InnerO.ID = InnerSO.OrderID
INNER JOIN OrderComponent InnerOC ON SO.ID = OC.SubOrderID
WHERE OC.OrderComponentTypeID IN (1,2,4,5)
AND EXISTS (SELECT * FROM OrderQuoteLineItem InnerOQLI
WHERE InnerOQLI.OrderQuoteLineItemTypeID = 9 AND Order.ID = InnerO.ID)
GROUP BY InnerO.ID)
),
您可以看到我尝试执行减法的位置,但它无法识别InnerOQLI,我尝试添加它以执行减法。我无法弄清楚如何纠正这一点,我意识到它无法完全识别InnerOQLI
,因为它存在于Exists声明中,是否存在于此?如果有人可以提供帮助,我会很感激
由于
答案 0 :(得分:0)
我不必尝试在CTE范围内执行减法,而只需将其放入主查询列表中使用此特定CTE的子查询中。
问题是,`InnerOQLI.FreePlaceCount未被识别,因为它没有在CTE范围内定义,只在Exists语句中使用。