Skip to content
Advertisement

Counting number of joined rows in left join

I’m trying to write an aggregate query in SQL which returns the count of all records joined to a given record in a table; If no records were joined to the given record, then the result for that record should be 0:

Data

My database looks like this (I’m not able to change the structure, unfortunately):

(MESSAGEPART has a composite PRIMARY KEY("MESSAGEID", "PARTNO"))

Desired output

Given the data above I should get something like this:

It seems obvious that I need to do a left join on the MESSAGE table, but how do I return a count of 0 for rows where the joined columns from MESSAGEPART are NULL? I’ve tried the following:

Logic

I’ve tried

However, this returns

I’ve also tried

but this returns

What am I doing wrong here?

Advertisement

Answer

How about something like this:

The COUNT() function will count every row, even if it has null. Using SUM() and CASE, you can count only non-null values.

EDIT: A simpler version taken from the top comment:

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