如何在SQL Server 2008中计算累积产品?

时间:2016-03-01 08:31:30

标签: sql sql-server sql-server-2008

我的桌子下面有2列,DATE&因子。我想计算累积产品,比如SQL Server 2008中的CUMFACTOR。

有人可以建议我一些替代方案。enter image description here

3 个答案:

答案 0 :(得分:1)

不幸的是,SQL Server(或大多数其他SQL数据库)中没有PROD()聚合或窗口函数。但你可以这样模仿它:

SELECT Date, Factor, exp(sum(log(Factor)) OVER (ORDER BY Date)) CumFactor
FROM MyTable

答案 1 :(得分:1)

您可以通过以下方式完成:

SELECT A.ROW
    , A.DATE
    , A.RATE
    , A.RATE * B.RATE AS [CUM RATE]
FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY DATE) as ROW, DATE, RATE
    FROM TABLE
) A
LEFT JOIN (
    SELECT ROW_NUMBER() OVER(ORDER BY DATE) as ROW, DATE, RATE
    FROM TABLE
) B
ON A.ROW + 1 = B.ROW

答案 2 :(得分:1)

要计算原始帖子中 CumFactor 列中显示的累积产品,以下代码可以完成此任务:

--first, load the sample data to a temp table
select *
into #t
from 
(
  values
  ('2/3/2000', 10),
  ('2/4/2000', 20),
  ('2/5/2000', 30),
  ('2/6/2000', 40)
) d ([Date], [Rate]);

--next, calculate cumulative product
select *, CumFactor = cast(exp(sum(log([Rate])) over (order by [Date])) as int) from #t;

结果如下:
enter image description here