HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Calculating the percentage change from the previous row

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
thepreviouscalculatingrowfromchangepercentage

Problem

I just entered the world of window functions. I have a similar problem to solve as in this question.

I have this table:

The last column (%Grown) is given by:

-(1 - price of row 2 / price of row 1) * 100


All the information I have found so far was related to sums, avg for all rows. I don't know how to bound two rows so I can calculate the percentage.

How do I translate this into SQL?

Solution

The best way I think would be to use the LAG() or LEAD() functions:

SELECT *, 
       - 100.0 * (1 - LEAD(Price) OVER (ORDER BY t.Id) / Price) AS Grown
FROM table_name AS t
ORDER BY t.Id ;


With LEAD(Price) OVER (ORDER BY t.Id) you have access to the next Price when the rows are ordered by Id. It's not clear what the order should be. Based on the data in the question, you may want (ORDER BY Price DESC).

Code Snippets

SELECT *, 
       - 100.0 * (1 - LEAD(Price) OVER (ORDER BY t.Id) / Price) AS Grown
FROM table_name AS t
ORDER BY t.Id ;

Context

StackExchange Database Administrators Q#112391, answer score: 11

Revisions (0)

No revisions yet.