Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Display the table and its job by yes and no

Tags:

sql

sql-server

This is my table:

User Table

Id | Username |
---------------
1  | jdoe     |

Job Table

Id | Job       |
----------------
1  | Waiter    |
2  | Office    |
3  | Freelance |

User Job Table

Id |UserId | JobId |
--------------------
1  | 1     | 2     |
2  | 1     | 3     |

How to select this table and display it to look like this below:

Id | Username | Waiter| Office | Freelance|
-------------------------------------------
1  | jdoe     | No    | Yes    | Yes      |
like image 371
saf21 Avatar asked Nov 28 '25 21:11

saf21


1 Answers

This is a pretty standard pivot query question, with an additional slight twist. In case a given user does not have a certain type of job assigned, you want to display 'No'. One way to do this is to make use of COALESCE and replace NULL job aggregates.

SELECT u.Id,
       u.Username,
       COALESCE(MAX(CASE WHEN j.Job = 'Waiter'    THEN 'Yes' END), 'No') AS Waiter,
       COALESCE(MAX(CASE WHEN j.Job = 'Office'    THEN 'Yes' END), 'No') AS Office,
       COALESCE(MAX(CASE WHEN j.Job = 'Freelance' THEN 'Yes' END), 'No') AS Freelance
FROM User u
LEFT JOIN User_Job uj
    ON u.Id = uj.UserId
LEFT JOIN Job j
    ON uj.JobId = j.Id
GROUP BY u.Id,
         u.Username
like image 130
Tim Biegeleisen Avatar answered Nov 30 '25 11:11

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!