moe
moe

Reputation: 5249

how to calculate growth percentage using sql

I am trying to calculate the the percentage change from one quarter to another quarter. I am not able to figure out one issue here is my query

SELECT YearKey,
sum(Q1)Q1, sum(Q2)Q2, sum(Q3)Q3, sum(Q4)Q4
FROM myTable
group by YearKey

The result of this query would look like this: enter image description here

But I want to add a new row for %change and total column at the end and here is the output I would like to see enter image description here

Upvotes: 2

Views: 10988

Answers (1)

Frederick
Frederick

Reputation: 169

I believe the equation needed to compute for the percentage growth is

GDP = (GDPn - GDPo) / GDPo

This will yield a decimal growth rate. Multiply it with 100 to get percentage.

Just incorporate it in the SQL Query Statement.

SELECT 
  YearKey,
  Q1 = sum(Q1),
  Q2 = sum(Q2),
  Q2Q1percentage = ((sum(Q2) - sum(Q1)) / sum(Q1))*100,
  Q3 = sum(Q3),
  Q3Q2percentage = ((sum(Q3) - sum(Q2)) / sum(Q2))*100,
  Q4 = sum(Q4),
  Q4Q3percentage = ((sum(Q4) - sum(Q3)) / sum(Q3))*100
FROM 
  myTable
GROUP BY YearKey

Upvotes: 2

Related Questions