I have three tables (for sake of argument) individual, email and attribute. individual_Ref the foreign key that links individual to email and attribute.
It isn't necessary for a given individual to be represented on the attribute table as they may never have had an attribute added and they can appear more than once if they have more than one attributes.
I want get a list of individual references and a count of a particular attribute for them. But need to search by email address as it is allowed for individuals to share email addresses (don't get me started)...
My first stab was
select e.individual_ref, count(a.attr_Code_ref)
from email e left join attribute a on e.individual_Ref = a.individual_ref
where e.email_Address = '[email protected]'
and a.attr_code_Ref = 4119
group by e.individual_ref
using a left join to ensure I get an individual ref from email if one exists and to ensure I get a result if there is an individual ref in email but not in attribute. Or so I thought since this returns no rows but...
select e.individual_ref,
(select count(a.attr_Code_ref) from attribute a where a.attr_code_Ref = 4119 and a.individual_ref = e.individual_ref)
from email e
where e.email_Address = '[email protected]'
group by e.individual_REf
returns one row with an individual_Ref and a count of 0
I'm not suggesting SQL is broken more that my understanding is... so I guess "what's my confusion?" is the question.