Skip to content
Advertisement

SQL left join with 2 or more count group

My table

expect result (count not sum)

My query

Try to have both count columns catone and cattwo
Not sure how to correct it. Thank you

Advertisement

Answer

A simple group-by should do it

Note that this simply counts the number of values that are not NULL. If your original data was this…

… then the result would be

If you want to count the distinct values – so totalcat2 would be 1 (as only 1 value exists in that column, although it’s there twice) you could use

which would return totalcat1 = 3 and totalcat2 = 1.

Here’s a db<>fiddle with the two options.

Here’s a second db<>fiddle on request of OP with ID 200.

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