You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

T-SQL计算各FundType加权绩效遇聚合函数嵌套报错求解决

问题:按FundType计算加权绩效时的T-SQL聚合错误

表结构与数据

SQL Server中存在FundAllocation表,结构及数据如下:

FundIDFundTypeAllocationPerformance
1Credit0.100.15
2Credit0.200.25
3Credit0.300.35
4Credit0.400.45
5Credit0.500.55
6Equity0.600.65
7Equity0.700.75
8Equity0.800.85
9Cash0.900.95
10Cash0.991.55

需求

为每个FundType计算加权绩效(WeightedPerformance),公式为:

WeightedPerformance = SUM( (Allocation / SUM(Allocation Per FundType)) * Performance )

以Credit类型为例:

  • 该类型总分配额:0.10+0.20+0.30+0.40+0.50 = 1.50
  • 加权绩效计算:((0.1/1.5)*0.15) + ((0.2/1.5)*0.25) + ((0.3/1.5)*0.35) + ((0.4/1.5)*0.45) + ((0.5/1.5)*0.55) = 0.416666666666667

错误的T-SQL语句及报错

当前编写的查询语句:

SELECT 
        FundType, 
        Sum((Allocation/Sum(Allocation))*Performance) as WeightedPerformance 
FROM
       FundAllocation
GROUP BY
       FundType

执行时报错:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

错误原因

SQL Server不允许在同一个聚合层级中嵌套使用聚合函数(比如外层SUM里嵌套内层SUM(Allocation)),分组聚合时内层聚合无法直接获取当前分组的总分配额。

解决方案

方法1:使用窗口函数计算分组总分配额

通过窗口函数SUM(Allocation) OVER (PARTITION BY FundType)先获取每个FundType的总分配额,再计算加权值后聚合:

SELECT 
    FundType,
    SUM((Allocation / TotalAllocation) * Performance) AS WeightedPerformance
FROM (
    SELECT 
        FundType,
        Allocation,
        Performance,
        SUM(Allocation) OVER (PARTITION BY FundType) AS TotalAllocation
    FROM FundAllocation
) AS SubQuery
GROUP BY FundType;

方法2:使用子查询预计算分组总分配额

先通过子查询统计每个FundType的总分配额,再关联原表计算加权绩效:

SELECT 
    fa.FundType,
    SUM((fa.Allocation / ft.TotalAllocation) * fa.Performance) AS WeightedPerformance
FROM FundAllocation fa
JOIN (
    SELECT FundType, SUM(Allocation) AS TotalAllocation
    FROM FundAllocation
    GROUP BY FundType
) ft ON fa.FundType = ft.FundType
GROUP BY fa.FundType;

验证结果

执行上述任一正确语句,将得到如下结果:

FundTypeWeightedPerformance
Cash1.27707547169811
Credit0.416666666666667
Equity0.756666666666667

内容的提问来源于stack exchange,提问作者developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 06:16:15