Growth Calculation Percentage Between Two Periods

I have a database with one table of complaints and the date they were sent. I have to do this, given the start and end dates of the two periods, I have to calculate the percentage of growth between them.

For instance:

  • Q1 (January-March) Claims = 200

  • Q2 (April - June) Claims = 400

To calculate height:

  • (present - past) / past * 100

  • Growth Percentage = (400 - 200) / 200 * 100 = 100% Growth

The information I must extract from this report, which claims grew 100% between Q1 and Q2

Here is what I came up with:

SELECT (SELECT COUNT(id) FROM complaints WHERE submit_date >= start_date_period_1 AND submit_date <= end_date_period_1) AS q1_claims, (SELECT COUNT(id) FROM complaints WHERE submit_date >= start_date_period_2 AND submit_date <= end_date_period_2) AS q2_claims, (SELECT ((q2_claims - q1_claims)/q2_claims * 100) AS 'Percentage Growth') FROM complaints; 

but does not show the result in the correct form. It shows an entry for each date for a given period. How can I fix the request?

+5
source share
1 answer

In the original query, you mixed aggregates (i.e. COUNT ) and non-aggregate columns, forcing MySQL to provide a result set containing an entry for each row. Instead, try using this query:

 SELECT ((q2.claims - q1.claims)/q2.claims * 100) AS 'Percentage Growth' FROM (SELECT COUNT(id) AS claims FROM complaints WHERE submit_date >= start_date_period_1 AND submit_date <= end_date_period_1) AS q1, (SELECT COUNT(id) AS claims FROM complaints WHERE submit_date >= start_date_period_2 AND submit_date <= end_date_period_2) AS q2 
+5
source

All Articles