如何返回一个列是子查询结果的行并返回另一个最高为0的列或相同子查询的结果?

时间:2014-01-14 16:40:17

标签: sql sql-server-2008

您能告诉我如何让下面的代码工作吗?

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'无效。

2 个答案:

答案 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,因为它在作业旁边的选择中无效