2

我正在研究 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 函数。但我需要用这个案例陈述求和。

4

2 回答 2

5

的确; 那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
于 2013-07-12T10:06:46.393 回答
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

上面的查询可能无法立即使用,因为没有太多信息可以使用

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

于 2013-07-12T10:16:28.807 回答