在包含聚合的表达式上执行聚合函数

问题描述 投票:0回答:0

Fundid fundtype合同 1Credit0.100.152Credit0.200.253Credit0.300.354Credit0.400.455Credit0.500.556equity0.600.657equity0.700.758equity0.800.859Cash0.900.9510Cash0.991.55WeightedPerformance = SUM ( (Allocation/SUM(Allocation Per FundType) * Performance) 信用示例:
绩效
我想根据以下公式来得出每种基金类型的加权性能:
Sum of Allocation = 1.50 (0.10+0.20+0.30+0.40+0.50) WeightedPerformance = Sum(((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) ) WeightedPerformance of Credit = 0.416666666666667

如何使用每个funcete的T-SQL对此进行计算? 到目前为止,Query:
SELECT 
        FundType, 
        Sum((Allocation/Sum(Allocation))*Performance) as WeightedPerformance 
FROM
       FundAllocation
GROUP BY
       FundType

但是得到:

Cannot在包含聚合或子查询的表达式上执行聚合函数。

注:这个问题不是

SQLServer的重复,“无法在包含聚合或子查询的表达式上执行汇总函数”,但是Sybase可以使用,因为建议的问题是使用子句分组的,以进行进一步汇总。在这种情况下,它由Fundtype分组。

您可以使用窗口函数为此

WITH summed AS ( SELECT fa.*, SUM(fa.Allocation) OVER (PARTITION BY fa.FundType) AS AllocationPerFundType FROM FundAllocation fa ) SELECT fa.FundType, SUM(fa.Allocation / fa.AllocationPerFundType * fa.Performance) as WeightedPerformance, SUM(Allocation) AS SumAllocation FROM summed fa GROUP BY fa.FundType;

sql t-sql group-by
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.