I have this request, which basically gets the average customer expenses for the last year and 3 months:
SELECT SQL_CALC_FOUND_ROWS customer_id, customer_name, AVG(IF( DATE(CONCAT(year_of_spend, "-", month_of_spend, "-01")) >= DATE_FORMAT(NOW() - INTERVAL 1 YEAR, "%Y-%m-01"), spend_amount, NULL )) AS 1_year_average_spend, AVG(IF( DATE(CONCAT(year_of_spend, "-", month_of_spend, "-01")) >= DATE_FORMAT(NOW() - INTERVAL 3 MONTH, "%Y-%m-01"), spend_amount, NULL )) AS 3_month_average_spend FROM customer_spends GROUP BY customer__id
But I also need to get the percentage difference in average costs:
eg. (pseudo code)
if (1_year_average_spend = 0) change = N/A else change = 3_month_average_spend / 1_year_average_spend - 1
How can or what do you recommend to implement this?
The only way I can think of is terrible:
IF( AVG(IF( DATE(CONCAT(year_of_spend, "-", month_of_spend, "-01")) >= DATE_FORMAT(NOW() - INTERVAL 1 YEAR, "%Y-%m-01"), `spend_amount`, NULL )) > 0, AVG(IF( DATE(CONCAT(year_of_spend, "-", month_of_spend, "-01")) >= DATE_FORMAT(NOW() - INTERVAL 3 MONTH, "%Y-%m-01"), spend_amount, NULL )) / AVG(IF( DATE(CONCAT(year_of_spend, "-", month_of_spend, "-01")) >= DATE_FORMAT(NOW() - INTERVAL 1 YEAR, "%Y-%m-01"), `spend_amount`, NULL )) - 1, "N/A" ) AS 3_month_performance