如何计算SQL Server 2008中的累积产品?
答
不幸的是,在SQL Server(或其他大多数SQL数据库)中没有PROD()
聚合或窗口函数。但是你可以模仿它是这样:
SELECT Date, Factor, exp(sum(log(Factor)) OVER (ORDER BY Date)) CumFactor
FROM MyTable
答
你可以做到这一点:
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
+0
在2005年版本中引入了“LEAD/LAG”,同时在2005年进行了排名功能。 –
答
计算累积的产品,如在原岗位显示在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;
你的数据中是否有ROW列? – Jodrell
[相关问题](http://stackoverflow.com/q/3912204/521799) –