Home Forums SQL Server 2005 SQL Server Newbies Query to find records in one table that have a specific number of records in another table RE: Query to find records in one table that have a specific number of records in another table

  • It should work if you remove the COUNT from the SELECT list. If it doesn't, then perhaps post your code (plus a full repro script - i.e. CREATE TABLE statements and INSERT statements so that we can recreate the issue without having to guess).

    However, if the requirement is just to find rows that have (at least one) matching row in SubTable1 and (exactly) two matching rows in SubTable2, then I would use this pattern:

    WHERE EXISTS (SELECT * FROM correlated subquery for SubTable1)

    AND (SELECT COUNT(*) FROM correlated subquery for SubTable2) = 2


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/