I have two tables I need to join:
Table_1
| user_id | name |
| ——– | ——– |
| 1 | John |
| 2 | Bob |
Table_2
| user_id | category | value |
| ——–| ——– | ————— |
| 1 | A | AB123 |
| 1 | B | CD789 |
| 1 | C | FF222 |
| 2 | B | CD123 |
I am trying to join them in a way to get the result below:
Result
| name | A value | B value |
| —- | ——- | ——————- |
| John | AB123 | CD789 |
| Bob | NULL | CD123 |
I’ve only been able to accomplish this by using the following two separate joins:
select t1.name, t2a.value, t2b.value
from Table_1 t1
left join Table_2 t2a
on t2a.category = ‘A’
and t1.user_id = t2a.user_id
left join Table_2 t2b
on t2a.category = ‘B’
and t1.user_id = t2a.user_id
Is there a way to write this as just one join?
DrDipply is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.