2013-07-12 66 views
2

我正在使用SQL Server 2008 R2。我正在努力獲得這筆錢。在SQL Server中對SUM函數使用CASE語句

這是我的查詢

select 
    SUM(
    case 
     when sec.SecurityTypeID = 2 then SUM(quantity)*(sec.AnnualIncomeRate/100) 
     when sec.SecurityTypeID = 5 then 0 
     when sec.SecurityTypeID = 11 then SUM(quantity)*sec.AnnualIncomeRate  
     else SUM(quantity)*sec.AnnualIncomeRate 
    end 
) AS ProjectedIncome 
from Transactions as t 

當我執行它給我下面的錯誤。

消息130,級別15,狀態1,第3行
不能對包含聚合或子查詢的表達式執行聚合函數。

我知道我使用sum函數和case子句。但我需要找到與這個案例陳述的總和。

回答

5

確實; case是每行,因爲您沒有group;當提到單行時,SUM(quantity)在很大程度上毫無意義。如果這是整個集合上的SUM,則必須將該第一個計算爲一個變量。否則,您需要考慮您想要應用的內部組/分區。

舉一個類似的例子:

這工作:

select 1 as [a], 2 as [b], 3 as [c] 

和這個作品:

select case [a] when 1 then [b] else [c] end from (
    select 1 as [a], 2 as [b], 3 as [c] 
) x 

但這並不:

select case [a] when 1 then sum([b]) else [c] end from (
    select 1 as [a], 2 as [b], 3 as [c] 
) x 

同樣,這作品:

select sum(case [a] when 1 then [b] else [c] end) from (
    select 1 as [a], 2 as [b], 3 as [c] 
) x 

,但是這不,給你報道的相同的錯誤消息:

select sum(case [a] when 1 then sum([b]) else [c] end) from (
    select 1 as [a], 2 as [b], 3 as [c] 
) x 
+0

謝謝馬克你給我更好的理解。目前我從其他人那裏得到案件查詢,所以這就是我爲什麼混淆。但你我更好理解。再次感謝。 –

0

不知道是什麼秒,在這種情況下,但我想借此創造派生表

select SUM(t.caseValue) AS ProjectedIncome 
from (select * , case 
     when sec.SecurityTypeID = 2 then (quantity)*(sec.AnnualIncomeRate/100) 
     when sec.SecurityTypeID = 5 then 0 
     when sec.SecurityTypeID = 11 then (quantity)*sec.AnnualIncomeRate  
     else (quantity)*sec.AnnualIncomeRate 
end as caseValue from Transactions) as t 

上面的查詢可能不會工作,因爲沒有太多的信息可以使用

A上面的nswer解釋了爲什麼查詢不能比我的工作好得多