Skip to content
Advertisement

Count number of instances of a specific value and join results with another table

I have 2 tables: Table 1 (User) contains names of users/leaders and Table 2 (Transactions) contains records of user transactions with a column named “reason”

There are several “reasons” which can be grouped into 2 categories.

I’m trying to count the number of transactions a user has made and group them into those 2 categories.

I have tried the following code which can get the count for Category 1 reason but is only showing users that have that reason. I was aiming to also show users without that reason but with a count of 0. This query also falls short of counting Category 2 Reason (I can’t even get near that just yet without breaking this simple one)

My expected result is:

but I am getting:

Thank you in advance for any help

Advertisement

Answer

I think you want conditional aggregation:

Note that this also uses a LEFT JOIN to keep all rows in users, if when there are no transactions at all.

If you want separate columns for each category reason, then extend the above logic:

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