I've been trying to calculate year over year growth for monthly returns and have been rewriting the same queries for hours with no luck. I've seen solutions but they're all other database solutions.
I'm trying to basically achieve something like the following:
And this is the query I've built, although I've never actually had it complete running (been running 15+ minutes) due to the sub-query runs per-row.
This table has 2m+ rows with good indexes, it's fast but subqueries kill it.
Could be totally wrong approach, but this is what I've got.
SELECT
YEAR(thisyear.trandte) AS `Year`,
MONTH(thisyear.trandte) AS `YearMonth`,
SUM(lastyear.totamount) AS LastYearSales,
SUM(thisyear.totamount) AS ThisYearSales
FROM
sync_invoice_lines thisyear
LEFT JOIN
sync_invoice_lines lastyear ON
MONTH(thisyear.trandte) = (MONTH(lastyear.trandte)) AND
YEAR(thisyear.trandte) = (YEAR(lastyear.trandte) - 1)
WHERE
thisyear.type = 'IN' AND
lastyear.type = 'IN' AND
thisyear.sync_active = 1 AND
lastyear.sync_active = 1 AND
GROUP BY `Year`, `YearMonth`