I have the following tables in my PostgreSQL database:
- classes: Containing class_id and other fields
- athletes: Containing athlete_id and other fields
- classes_athletes: This is a many to many relationship between classes and athletes. It contains for each class_id which athlete_id are enrolled. In my case it looks like this:
select * FROM classes_athletes;
class_id | athlete_id
-------------------+------------
2 | 1
2 | 2
2 | 3
2 | 4
2 | 5
1 | 1
1 | 2
1 | 3
1 | 4
Now what I would like to do is to create an SQL query which I can use to indicate if a class contains or not a certain athlete. Here are some examples based on the data above:
For athlete_id=1 it should return
class_id | athleteIsEnrolled
----------+------------------
1 | 1
2 | 1
For athlete_id=99 it should return
class_id | athleteIsEnrolled
----------+------------------
1 | 0
2 | 0
I Tried the following sql query but it returns a value for each entry of classes_athletes instead of only one for each unique class_id:
SELECT c.class_id, CAST(CASE WHEN athlete_id = 1 THEN 1 ELSE 0 END AS bit) as athleteEnrolled
FROM classes_athletes as c;
And the result is:
class_id | athleteEnrolled
-------------------+-----------------
2 | 1
2 | 0
2 | 0
2 | 0
2 | 0
1 | 1
1 | 0
1 | 0
1 | 0