Skip to content
Advertisement

SQLite – calculate percentage increase in values of a numeric column

I am interested in getting the % increase or decrease of the values in one column with respect to the previous value.

Can someone please advice how I should do this?

Thanks

This is what my table looks like

week |  sales  |

22   |  11     |
21   |  63     |
20   |  78     |
19   |  170    |
18   |  130    |

And this is what I would like

week |  sales  | growth

22   |  11     | -82.5
21   |  63     | -19.2
20   |  78     | -54.12
19   |  170    | 30.8
18   |  130    | NULL

Advertisement

Answer

Use LAG() window function to get the previous value of sales for each week:

SELECT *,
       ROUND(100.0 * (1.0 * sales / LAG(sales) OVER (ORDER BY week) - 1), 1) growth
FROM tablename
ORDER BY week DESC;

See the demo.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement