Search code examples
sql-serverdividecumulative-sum

Accessing prior rows and divide its value by current row


I have the rows below, and i want to access prior row and divide its value by current row. For every row, i need to calculate the Vi value, this Vi value is equal to Vi-1/Vi which means that:

Given the table

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

I want to generate these values

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

So at the end i want the following output:

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

I tried using the aggregate function SUM with OVER(), but i do not know how to solve this problem as i need to divide and not sum the value

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

Sample data:

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

Solution

  • Unfortunately, SQL do not have Product, but it should be simple to use cte. The performance should be not bad if id was indexed

    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