I've been spending 2 days working on this and cannot find anything help.
I have 2 tables.
1. players
id | name |
---|---|
1 | AA |
2 | BB |
3 | CC |
4 | DD |
2. matching
id | player_id | match_id | date | has_opponent |
---|---|---|---|---|
1 | 1 | 1 | 2021-06-23 | 0 |
2 | 2 | 1 | 2021-06-23 | 0 |
3 | 3 | 2 | 2021-06-21 | 0 |
4 | 4 | 3 | 2021-06-22 | 1 |
Expected Result
match_id | date | first_opponent_name | second_opponent_name |
---|---|---|---|
1 | 2021-06-23 | AA | BB |
2 | 2021-06-21 | CC | |
3 | 2021-06-22 | DD | DD |
I want to join these 2 tables with new columns ( first_opponent_name & second_opponent_name ) if it meets condition as below:
- If there is a duplicated match_id but it has different player_id, then display their names in 2 separated columns.
- If there is only 1 match_id and it has 1 player_id and has_opponent column is 0, then this should display only first_opponent_name
- If there is only 1 match_id and it has 1 player_id and has_opponent column is 1, then first_opponent_name and second_opponent _name should be displayed as the same value.