2011-10-27 160 views
0

我有這個疑問集團通過查詢和SQL Server 2008

select SUM(Qty) as Qty 
from WorkTbl group by Status 
having Status = 'AA' or Status = 'BB' 

該查詢返回2行(100和500)

如何總結這些2行?

回答

3

拿出GROUP BY,並用WHERE代替HAVING

select SUM(Qty) as Qty 
from WorkTbl 
where Status = 'AA' or Status = 'BB' 

或者,如果有更多的查詢,以及您希望保留目前大部分的結構,把它變成一個子查詢(或CTE):

select SUM(Qty) from (
select SUM(Qty) as Qty 
from WorkTbl group by Status 
having Status = 'AA' or Status = 'BB' 
) t 

(我們必須包括t最後,因爲from子句中的每一行都必須有一個名稱 - 它可以是任何東西)