Skip to content
Advertisement

Can I Select DISTINCT on 2 columns and Sum grouped by 1 column in one query?

Is it possible to write one query, where I would group by 2 columns in a table to get the count of total members plus get a sum of one column in that same table, but grouped by one column?

For example, the data looks like this

enter image description here

I want to get a count on distinct combinations of columns “OHID” and “MemID” and get the SUM of the “Amount” column grouped by OHID. The result is supposed to look like this

enter image description here

I was able to get the count correct using this query below

However, when I try to use this query below to get all the results together, I am getting a count of 15 and a totally different total sum.

Advertisement

Answer

If I understand correctly, you want to consider NULL as a valid value. The rest is just aggregation:

The case logic might be a bit off-putting. It is just adding 1 if any values are NULL.

You might find this easier to follow with two levels of aggregation:

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