I’m trying to run a query which counts the number of orders each user has made. Unfortunately, the system was not set up well initially and there are a number of duplicate customer records (using the same email address).
I currently have the following simple query:
SELECT
u.id,
u.name
u.email,
COUNT(o.id) AS num_orders
FROM users u
INNER JOIN orders o
ON o.user_id = u.id
GROUP BY u.id
ORDER BY u.id
Is there anything I can do to it to merge the counts for duplicate users?
Any advice appreciated.
Thanks
Incidentally, while mysql allows you to do
GROUP BY u.idand omit the other non-aggregate fields in your query, it is not good nor standard SQL and should be avoided.