0

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

1 Answer 1

1
SELECT  
    u.email, 
    COUNT(o.id) AS num_orders 
FROM users u 
    INNER JOIN orders o 
        ON o.user_id = u.id 
GROUP BY u.email
ORDER BY u.email 

Incidentally, while mysql allows you to do GROUP BY u.id and omit the other non-aggregate fields in your query, it is not good nor standard SQL and should be avoided.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.