将百分比表示为总体积的百分比而不是排名体积

express percent as a percentage of the total volume rather than ranked volume

鉴于此查询:

select      [Code],         
            [EffectiveDate],
            [Volume] = Sum(Volume),
            [VolumeRank] = RANK() OVER (PARTITION BY EffectiveDate ORDER BY SUM(Volume) DESC),
            [VolumePercent] = PERCENT_RANK() OVER (PARTITION BY EffectiveDate ORDER BY SUM(Volume) ASC)
from        CodeTable
where       EffectiveDate between @start and @end
group by    DerivativeType, MemberCode, EffectiveDate

产生这些结果

X   2014-05-02 00:00:00.000 15683.00    1   1
X   2014-05-05 00:00:00.000 10524.00    1   1
Y   2014-05-05 00:00:00.000 8318.00     2   0.99236641221374
Y   2014-05-02 00:00:00.000 8264.00     2   0.991935483870968

体积百分比正在计算 排名 百分比,这是有道理的!
我想使用类似的函数 return 总体积的百分比体积 在日期内分区,而不是排名百分比。

只见树木不见森林...

有什么想法吗?

然后您想使用 window 函数来计算总体积。我认为逻辑是:

select sum(volume) / sum(sum(volume)) over (partition by EffectiveDate)

如果volume是一个整数,你应该把它转换成一个非整数。否则,除法将 return 一个整数——并且是 0 或 1。我经常通过乘以 1.0:

来做到这一点
select sum(volume*1.0) / sum(sum(volume)) over (partition by EffectiveDate)

构造 sum(sum(volume)) 第一次看到它时看起来很奇怪。内部 sum() 用于 group by。外层 sum() 用于 window 函数——获取聚合后的总数。