How to Calculate ROI for Date Range in MySQL

database-designMySQL

I have a SELECT with calculated columns and Im doing some filtering on it.

The issue Im having with ROI where Im calculating average for the date range, which is incorrect as ROI needs to be calculated from actual revenue and costs (ie. ROI = (revenue-costs/costs)*100 )

So the question is, how I can calculate the correct ROI?

SELECT 
                 c.campaign_name, 
                 c.traffic_source_name, 
                 cvr.custom_variable, 
                 SUM(cvr.visits) as visits, 
                 SUM(cvr.clicks) as clicks, 
                 AVG(cvr.ctr) as ctr, 
                 SUM(cvr.conversions) as conversions, 
                 SUM(cvr.cost) as cost, 
                 SUM(cvr.revenue) as revenue, 
                 SUM(cvr.profit) as profit, 
                 ROUND(AVG(cvr.roi), 2) as roi,
                 AVG(cvr.ap) as ap
                 FROM custom_variable_report as cvr
                 INNER JOIN campaigns as c
                 ON c.campaign_id = cvr.campaign_id AND c.date = cvr.date
                 WHERE cvr.campaign_id = 'b881eb19-8a47-4a60-9373-b0981006733a' 
                 AND (cvr.date BETWEEN '2017-03-03' AND '2017-03-09')
                 GROUP BY cvr.custom_variable
                 HAVING ABS(profit) > 2.51*1
                 AND roi < -25
                 ORDER BY cvr.profit ASC

In this case if I have 2 data points: -20% and 100% the average is: 40% which is incorrect as ROI needs to be reflected from the revenue and costs instead for each row.

Best Answer

Unless I'm missing something, wouldn't it be:

ROUND((SUM(revenue) - SUM(cost)) * 100.0 / SUM(cost), 2) as roi