I have a difficult operation that must be performed within SQL due to operational limitations.
I have 3 tables that contain required information. They each have some common columns that can be used for a join but do not have a single one that all three share.
The 3 tables are:
Table 1:
| rule_type | code |
|-----------|------|
| Type A | A1 |
| Type A | A1 |
| Type B | B1 |
| Type B | B1 |
| Type C | C1 |
| Type C | C1 |
Table 2:
| site_ref | code |
|----------|------|
| XYZ | A1 |
| XYZ | A1 |
| XYZ | C1 |
| XYZ | C1 |
Table 3:
| site_ref | population |
|----------|------------|
| XYZ | 100 |
| XYZ | 100 |
| XYZ | 100 |
The JOIN required must contain all 3 columns and an additional one that counts the number of distinct entries from table 1. The desired outcome would be:
| rule_type | code | site_ref | population | count |
|-----------|------|----------|------------|-------|
| Type A | A1 | XYZ | 100 | 2 |
| Type B | B1 | XYZ | 100 | 0 |
| Type C | C1 | XYZ | 100 | 2 |
I have attempted to create this joining on common columns via a FULL OUTER JOIN:
SELECT code, count(*) as count, site_ref, population, rule_type, population
FROM
(SELECT A.code, count(*) as count, B.site_ref, C.population, A.rule_type
FROM table_1 as A
FULL OUTER JOIN table_2 AS B ON A.code = B.code
JOIN table_3 as C ON B.site_ref = C.site_ref
WHERE site_ref = 'XYZ' AND rule_type in ('Type A', 'Type B', 'Type C'))
GROUP BY code, count(*) as count, site_ref, population, rule_type, population
But this is returning:
| rule_type | code | site_ref | population | count |
|-----------|------|----------|------------|-------|
| Type A | A1 | XYZ | 100 | 2 |
| Type C | C1 | XYZ | 100 | 2 |
As because there is no corresponding Type B count in table 2, it has nothing to count. I thought using a FULL OUTER JOIN would bring in these additional rule types but it hasn't. Is there a way to adapt the JOIN that will bring in the additional columns from table 1 and create an entry showing the columns of Type B but with a count of 0?