Skip to content
Advertisement

Aggregate function of column that has at least one type of value in a different column

I have table below as

How can I query my table above to get average of only my IDs that have at least have one row with blood type of A

Expected output:

Thanks!

Advertisement

Answer

Tim’s answer is good, a simpler albeit perhaps not how you would want to do it, other way, is doing HAVING in long form

so you can ether use SUM or COUNT, they both ignore nulls, which is the implicit result of Tim’s CASE WHEN Blood_Type = 'A' THEN 1 END is the same as

if you use SUM it can handle null’s or zeros thus the IFF can be used, which I like as it’s smaller and more explicit about what is happening.

thus Tim’s answer can be swapped to a SUM(IFF like:

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