我正在研究 SQL Server 2008 R2。我正在尝试计算总和。
这是我的查询
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
当我执行它时,出现以下错误。
Msg 130, Level 15, State 1, Line 3
Cannot perform an aggregate function on an expression containing an aggregate or a sub query.
我知道我正在使用带有 case 子句的 sum 函数。但我需要用这个案例陈述求和。
最佳答案
确实;该 case
是每行,因为您没有 group
; SUM(quantity)
在引用单行时基本上没有意义。如果这是整个集合的SUM
,您将必须首先将其计算到一个变量中。否则,您需要考虑您希望将内部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
关于sql - 在 SQL Server 中使用带有 SUM 函数的 CASE 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17612387/