tags:

views:

47

answers:

1

Say you have a user table and an order table which references user (user has_many orders) and contains an item count field.

How could you efficiently ask "how many uses ordered how many items?"

That is, to generate something along the lines of:

Number of users | sum of items
-------------------------------
5 users         | 1 item
4 users         | 5 items
1 user          | 7 items

Thanks in advance.

+1  A: 

You need to use a derived table:

SELECT COUNT(*) AS `Number of Users`, `Sum of Items` 
FROM (
    SELECT u.UserID, SUM(ItemCount) AS `Sum of Items`
    FROM User u
    INNER JOIN Order o ON u.UserID = o.UserID
    GROUP BY u.UserID
) g
GROUP BY `Sum of Items`
Bill Karwin
Perfect, that was exactly what I was looking for.
Daniel Johnson
Here the User table is unnecessary at all.
msi77
@msi77: Yes, true!
Bill Karwin