Luis Carías
Luis Carías

Reputation: 1

How to calculate difference from one month to another in SQL? (postgres)

I want to calculate the difference of leads from one month to another many times. Let´s say i had 1000 leads in july, 1200 leads in august and 1500 leads in september.

I know that I have to do final_var - initial_var / initial_var *100

How do i do it through SQL?

Upvotes: 0

Views: 48

Answers (1)

Teja Goud Kandula
Teja Goud Kandula

Reputation: 1574

Sample data structure:

CREATE TABLE leadsdata
(
    month integer,
    leads_count integer
)

Data as per you problem statement:

insert into leadsdata values
(7,1000),
(8,1200),
(9,1500)

The below is the SQL which you are trying to build:

select month, leads_count, 
lag(leads_count) over(order by month) ,
(( leads_count - lag(leads_count) over(order by month) ) / cast(lag(leads_count) over(order by month) as float) ) * 100
from LeadsData

Upvotes: 1

Related Questions