对产品进行汇总

更新页 :
页面创建日期 :

样本数据

只需定义一个仅具有年和利息的表,即可定义数据。

-- テーブル定義
declare @利息マスタ table 
(
  年月 nvarchar(6)
 ,利息 decimal(4, 2)
)

-- サンプルデータ挿入
insert @利息マスタ
          select N'201501', 1.05
union all select N'201502', 1.03
union all select N'201503', 1.02
union all select N'201504', 1.10
union all select N'201505', 1.02
union all select N'201506', 1.06
union all select N'201507', 1.07
union all select N'201508', 1.04
union all select N'201509', 1.06
union all select N'201510', 1.07
union all select N'201511', 1.03
union all select N'201512', 1.02

-- 確認
select * from @利息マスタ

累计乘积

乘积的聚合可以由“指数函数”和“对数函数”的聚合确定。 SQL 应如下所示:

-- 集計
select exp(sum(log([利息]))) from @利息マスタ
-- 結果:1.73968081491318

这可以通过“指数函数”和“对数函数”的性质来实现。

首先,对数函数的摘要根据公式为“日志 x + 日志 y = 日志 (x = y)”。 指数函数的公式“elogx = x**”表示“elog(x*y) = x = y”,如果应用对数函数的总和。 (x * y * ... 部分成为数据的数量)

零和负对应

由于对数函数不能小于或等于 0,因此,如果聚合包含小于或等于 0 的数字,则会发生错误。 要匹配小于或等于 0 的数字,SQL 如下所示:

-- 集計(ゼロ、負対応)
select
  case
    when min(abs([利息])) = 0 then 0
    else
       exp(sum(log(abs(nullif([利息], 0)))))
     * round(0.5 - count(nullif(sign(sign([利息]) + 0.5), 1)) % 2, 0)
  end as [利息合計]
from @利息マスタ
-- 結果:1.73968081491318