SQL Server中带SUM函数的用例语句

SQL Server中带SUM函数的用例语句,sql,sql-server,sql-server-2008-r2,Sql,Sql Server,Sql Server 2008 R2,我正在使用SQLServer2008R2。我正在设法算出总数 这是我的问题 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.Annu

我正在使用SQLServer2008R2。我正在设法算出总数

这是我的问题

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
应用于哪个组/分区

举一个类似的例子:

这项工作:

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 sum(case [a] when 1 then [b] else [c] end) from (
  select 1 as [a], 2 as [b], 3 as [c]
) x
这是有效的:

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 sum(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 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 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

不确定本例中的sec是什么,但我将使用它并创建一个派生表

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
上面的查询可能无法立即执行,因为没有太多信息可供处理


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

谢谢你给我更好的理解。目前,我从其他人那里得到了案例查询,所以我感到困惑。但你能让我更好地理解。再次感谢。