在SQL Server中使用带有SUM函数的CASE语句

时间:2013-07-12 10:03:36

标签: sql sql-server sql-server-2008-r2

我正在研究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
  无法对包含聚合或子查询的表达式执行聚合函数。

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

2 个答案:

答案 0 :(得分:5)

实际上;每行case,因为您没有group;当引用单行时,SUM(quantity)在很大程度上毫无意义。如果这是整个集合中的SUM,则必须将首先计算到变量中。否则,您需要考虑您希望内部的{/ 1}}应用于哪个组/分区。

举一个类似的例子:

这有效:

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

答案 1 :(得分: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
上面的

查询可能不会起作用,因为没有太多信息可以使用

上面的答案解释了为什么查询的效果不如我的