Skip to content
Advertisement

How to properly GROUP BY within a GROUP BY to get the COUNT of several COUNTS

So I need to get the count for the number items from found in different user accounts. Basically, the items are stored in lists, which are then stored in accounts. The issue is that the items have a list_id, but no account_id even though lists have an account_id. If there was also an account_id for items, it would be easy, but it goes more like this:

So there’s no direct connexion between account and item. I know this is not optimal, but I’m not the one who designed the database. I just have to work with it.

Here’s how the data is structured:

Here is the code that gets me the current results:

Here’s what I’ve tried to get the desired results:

However, when I do this, all I get is the count from one of the lists. So if list 1 from account 1 has 3 items, list 2 from account 1 has 4 items, I get a count of 3 even if I group the lists by account.

What I need is to get the count of all items within a list, then the count of all items within all list of an account.

Advertisement

Answer

As far as concerns, your current attempt is almost there. You just need to change the group by clause to match the non-aggregated column in the select clause:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement