I have 2 tables, one which is the master the other the details. They have a 1 to many relationship:
MasterTable
------------
id (pk)
col1
DetailTable
------------
id (pk)
mid (fk to MasterTable id)
col1
An example of how data would look would be as such:
MasterTable
ID
---
1
2
3
4
5
DetailTable
ID | MID | COL1 |
---|-------|-------|
1 1 BIRD
2 1 DOG
3 1 DOG --Duplicates are allowed for the same MID
4 1 CAT
5 2 CAT
6 5 FISH
For the detail table the possible values for col1 are:
- BIRD
- DOG
- CAT
- FISH
- MOUSE
I then need to create a query which will layout for each id in the master table to see if they have any of these values. So the final query result would look like this:
MasterID | BIRD | DOG | CAT | FISH | MOUSE
-----------------------------------------------------
1 Y Y Y
2 Y
3
4
5 Y
So I am collapsing the detail table into one row in the final result. I am unsure how to create this query though.
I was trying something like this, but it doesn't work:
SELECT MASTERTABLE.ID,
CASE WHEN DETAILTABLE.col1 = 'BIRD' THEN 'Y' ELSE NULL END AS BIRD,
CASE WHEN DETAILTABLE.col1 = 'DOG' THEN 'Y' ELSE NULL END AS DOG,
CASE WHEN DETAILTABLE.col1 = 'CAT' THEN 'Y' ELSE NULL END AS CAT,
CASE WHEN DETAILTABLE.col1 = 'FISH' THEN 'Y' ELSE NULL END AS FISH,
CASE WHEN DETAILTABLE.col1 = 'MOUSE' THEN 'Y' ELSE NULL END AS MOUSE
FROM MASTERTABLE LEFT JOIN DETAILTABLE ON MASTERTABLE.ID = DETAILTABLE.mid;