I have the following database schema (names changed to protect the innocent)
Code Table
| code_id | code_desc |
|---------|-----------|
| 1 | good |
|---------|-----------|
| 2 | bad |
|---------|-----------|
| 3 | ugly |
|---------|-----------|
Foo Table AssignedFoo Table
| foo_id | foo_desc | foo_dt | | assn_id | foo_id | code_id |
|--------|----------|-----------| |---------|--------|---------|
| 101 | red | 1/1/2000 | | 301 | 101 | 1 |
|--------|----------|-----------| |---------|--------|---------|
| 102 | green | 6/1/2000 | | 302 | 102 | 2 |
|--------|----------|-----------| |---------|--------|---------|
| 102 | blue | 12/1/2000 |
|--------|----------|-----------|
Bar Table AssignedBar Table
| bar_id | bar_desc | bar_dt | | assn_id | foo_id | code_id |
|--------|----------|-----------| |---------|--------|---------|
| 201 | gold | 12/1/2000 | | 401 | 201 | 1 |
|--------|----------|-----------| |---------|--------|---------|
| 202 | silver | 1/1/2001 | | 402 | 202 | 3 |
|--------|----------|-----------| |---------|--------|---------|
| 202 | bronze | 6/1/2001 |
|--------|----------|-----------|
I want to count the number of records that are mapped to the Code table regardless if they're foos or bars. I had though that the following query would work.
SELECT
COUNT(c.code_id) AS coded,
c.code_desc
FROM
code c
INNER JOIN assignedfoo af ON af.code_id = c.code_id
INNER JOIN foo f ON f.foo_id = af.foo_id
WHERE
f.foo_dt >= [start date] AND
f.foo_dt <= [end date]
GROUP BY
c.code_desc
UNION ALL
SELECT
COUNT(c.code_id) AS coded,
c.code_desc
FROM
code c
INNER JOIN assignedbar ab ON ab.code_id = c.code_id
INNER JOIN bar b ON b.bar_id = ab.bar_id
WHERE
b.bar_dt >= [start date] AND
b.bar_dt <= [end date]
GROUP BY
c.code_desc
Unfortunately, I get the following result set
| coded | code_desc |
|-------|-----------|
| 1 | good |
|-------|-----------|
| 1 | good |
|-------|-----------|
| 1 | bad |
|-------|-----------|
| 1 | ugly |
|-------|-----------|
What I want to get is this
| coded | code_desc |
|-------|-----------|
| 2 | good |
|-------|-----------|
| 1 | bad |
|-------|-----------|
| 1 | ugly |
|-------|-----------|
Any suggestions about how to fix this?
Any help would be greatly appreciated.
Thanks!