访问先前的行并将其值除以当前行

Accessing prior rows and divide its value by current row

我有下面的行,我想访问前一行并将其值除以当前行。对于每一行,我需要计算 Vi 值,这个 Vi 值等于 Vi-1/Vi 这意味着:

鉴于 table

Table T
id value out
1  100
2  200
3  10  
4  50 

我想生成这些值

V1 = 100
V2= 100/200 = 0.5
V3 = 0.5/10 = 0.05
V4 = 0.05/50 = 0.001

所以最后我想要以下输出:

id value out
1  100   100
2  200   0.5
3  10    0.05
4  50    0.001

我尝试将聚合函数 SUM 与 OVER() 一起使用,但我不知道如何解决这个问题,因为我需要对值进行除法而不是求和

    SELECT  id, value, SUM(value) OVER(ORDER BY id ROWS BETWEEN 
                                       1 PRECEDING AND 1 PRECEDING ) / value as out
    FROM T

示例数据:

CREATE TABLE t(
    id      INT,
    value   INT
);
INSERT INTO t VALUES
    (1, 100), (2, 200), (3, 10), (4, 50);

可惜SQL没有Product,不过用cte应该很简单。如果 id 被索引

性能应该不错
DECLARE @T table (id int identity(1,1) primary key, value int)
INSERT @T VALUES (100), (200), (10), (50)

;WITH cte AS
(
    SELECT id, value, CAST(value AS decimal(20,4)) AS out FROM @T WHERE id = 1
    UNION ALL SELECT T.id, T.value, CAST(cte.out / T.value AS decimal(20,4)) FROM cte INNER JOIN @T T ON cte.id = T.id - 1
)
SELECT * FROM cte