So I’m solving a question of a project, and I need to calculate the Compound Annual Growth Rate (CAGR), together with the total sales of the top 5 EV makers from fiscal year 2022 to 2024.
I found out the query to calculate the sales of the top five 5 makers from FY2022 to FY2024 using a query like this.
SELECT
maker,
SUM(electric_vehicles_sold) AS total_ev_sold
FROM new_schema.sales_by_makers
WHERE fiscal_year BETWEEN 2022 AND 2024 AND vehicle_category = '4-Wheelers'
GROUP BY maker
ORDER BY total_ev_sold DESC
LIMIT 5;
I also got the result as expected. output
Now adding the column for CAGR is the real problem, it should be something like this.
SELECT
maker,
SUM(electric_vehicles_sold) AS total_ev_sold,
((total_ev_sold / starting_point) ^1/2) - 1 AS CAGR
FROM new_schema.sales_by_makers
WHERE fiscal_year BETWEEN 2022 AND 2024 AND vehicle_category = '4-Wheelers'
GROUP BY maker
ORDER BY total_ev_sold DESC
LIMIT 5;
Unfortunately, I have no idea on how to get the starting_point
, which should be the total_ev_sold of fiscal year 2022. I’ve read many articles about calculating CAGR in SQL but none of them are appropriate in my case. Please give some help! Feel free to ask questions if you need more information.
2
Answers
Using CTE approach should give you the desired result.
See example
fiddle
All values in example completely made up for example.