您能告诉我如何让下面的代码工作吗?
SELECT OrderCount= (select Sum(Qty) from dbo.tblOrders WHERE OrderType in (4,6,8) )
- (select Sum(Qty) from dbo.tblOrders WHERE OrderType in (2,5,10) ) ,
CASE WHEN OrderCount < 0 THEN 0 ELSE OrderCount END AS TotalOrders
FROM dbo.tblOrders
我在上面的查询中遇到的错误是
Msg 207,Level 16,State 1,Line 4 列名称'OrderCount'无效。
答案 0 :(得分:4)
您不能在同一范围内引用列别名。
您需要子查询或CTE
:
WITH CTE AS
(
SELECT OrderCount = (SELECT Sum(qty)
FROM dbo.tblorders
WHERE ordertype IN ( 4, 6, 8 )) - (SELECT Sum(qty)
FROM dbo.tblorders
WHERE ordertype IN
( 2, 5, 10 ))
FROM dbo.tblorders
)
SELECT OrderCount,
TotalOrders = CASE WHEN OrderCount < 0 THEN 0 ELSE OrderCount END
FROM CTE
答案 1 :(得分:-1)
变量需要DECLARE
如此:
DECLARE @OrderCount int
SELECT @OrderCount= (select Sum(Qty) from dbo.tblOrders WHERE OrderType in (4,6,8) )
- (select Sum(Qty) from dbo.tblOrders WHERE OrderType in (2,5,10) )
FROM dbo.tblOrders
还取出了CASE,因为它在作业旁边的选择中无效