admin

在SQL Server中将CASE语句与SUM函数一起使用

sql

我正在使用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

当我执行它时,出现以下错误。

消息130,级别15,状态1,第3行
无法对包含聚集或子查询的表达式执行聚集功能。

我知道我正在使用带有case子句的sum函数。但是我需要用这个案例陈述来求和。


阅读 251

收藏
2021-06-07

共1个答案

admin

的确; 那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
2021-06-07