Top Customer by Orders
MediumPremium
You are given the following tables:
transactions table:
products table:
users table:
Write a query to find the name of the customer who has placed the largest number of orders in total. Your output should have the following column: user_id, name, orders (Total number of orders made by the user)
SELECT
user_id,
name,
COUNT(txns.id) orders
FROM transactions txns
JOIN users usrs
ON txns.user_id = usrs.id
GROUP BY
user_id,
name
ORDER BY
-- sort by the number of orders
COUNT(txns.id) desc
-- limit to top user
LIMIT 1
SELECT u.id as user_id, u.name, COUNT(t.product_id) AS orders FROM users u JOIN transactions t ON t.user_id = u.id JOIN products p ON p.id = t.product_id GROUP BY u.id, u.name ORDER BY orders DESC LIMIT 1