Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return results if count matches record count

I have 2 SQL server tables lets say called child and parent with one parent to many children. I have a field in parent called ChildrenCount and would like a query that will join and returns results only if the number of records in the child table matches ChildrenCount in the parent table. Is this possible in SQL or will this require a stored procedure?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You could use a join combined with aggregation:

SELECT p.id
FROM parent p
INNER JOIN child c
    ON c.parent_id = p.id
GROUP BY p.id, p.ChildrenCount 
HAVING p.ChildrenCount = COUNT(*);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading