I'm trying to get top buyers by email. I'm doing this by something like:
SELECT email, MAX(dt) FROM orders GROUP BY email ORDER BY COUNT(*) DESC;
This works, I get the top repeated rows grouped by email. So top orders by email, sorted in descending order.
The part I'm now stuck with is seeing only orders that were less than a month ago.
I've tried something like the following, but I get an error:
SELECT email, MAX(dt) FROM orders WHERE TIMESTAMPDIFF(MONTH,MAX(dt),NOW()) < 1 GROUP BY email ORDER BY COUNT(*) DESC;
Error:
Invalid use of group function
I've also tried using WHERE MAX(dt) between NOW() and NOW() - INTERVAL 1 MONTH
, and I get the same error.
Would anyone know how this could be done in MySQL?
The aim is only top orderers for those, who had an order in the last month.