Find list of GROUPIDs that have ZERO AccountIDs on another table

Find list of GROUPIDs that have ZERO AccountIDs on another table
typescript
Ethan Jackson

Looking for SQL that returns a list of GROUPIDs (from the ACCOUNT_GROUP) table that have no ACCOUNTS that are found on the ACCOUNT_LIST table.

ACCOUNT_GROUP (table)

GROUPIDACCOUNT
GROUP1111111
GROUP1222222
GROUP1333333
GROUP2222222
GROUP3333333
GROUP4444444

ACCOUNT_LIST (table)

ACCOUNT
111111
222222
444444

The result should return only GROUP3 since this is the only GROUPID that does not have at least one account in the ACCOUNT_LIST table.

I have tried a few WHERE NOT EXISTS, not getting the correct results

This returns GROUPIDs that have an Account that is not in the ACCOUNT_LIST table even if it has some that do exist (which is not what I need)

SELECT DISTINCT GROUPID FROM ACCOUNT_GROUP T1 WHERE NOT EXISTS ( SELECT 1 FROM ACCOUNT_LIST T3 WHERE T1.ACCOUNT = T3.ACCOUNT )

Answer

You can accomplish that in two steps:

  1. Determine for each ACCOUNT_GROUP row whether an entry exists in the ACCOUNT table
  2. Then aggregate by GROUPID and only keep groups for which there are no entries in the ACCOUNT table which we can do by summing the total of the calculated value ACCOUNT_EXISTS over all the rows with the same GROUPID.
SELECT GROUPID FROM ( SELECT * , CASE WHEN EXISTS (SELECT 1 FROM ACCOUNT A WHERE A.ACCOUNT = AG.ACCOUNT) THEN 1 ELSE 0 END ACCOUNT_EXISTS FROM ACCOUNT_GROUP AG ) x GROUP BY GROUPID HAVING SUM(ACCOUNT_EXISTS) = 0;

db<>fiddle

Related Articles