Skip to content
Advertisement

Is there a way to perform this inner join in sql?

I have a sql database with two tables. The first table is named Workers with columns: id, name and includes values:

1, Mark
2, David
3, Peter

The second is named WorkingHours with: id, hours, date and includes values:

1, 5, '2019-07-20'
1, 4, '2019-07-21'
3, 6, '2019-07-10'
3, 4, '2019-07-20'

I want to make a query that will show a view for ‘2019-07-20’ like this:

id     name       hours
1      Mark       5
2      David  
3      Peter      4

If my query is:

SELECT W.*, H.hours
  FROM Workers W
    INNER JOIN WorkingHours H ON W.id = H.id
  WHERE H.date = '2019-07-20'

I will not get David. How can I get him too?

Advertisement

Answer

You need to use left join and coalesce() to get 0 hours for the workers that do not have hours on ‘2019-07-20’

SELECT W.*, coalesce(H.hours, 0) hours 
FROM Workers W 
    LEFT JOIN WorkingHours H ON W.id = H.id AND H.date = '2019-07-20'

If you don’t want 0’s, use H.hours instead of coalesce(H.hours, 0) which will return null.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement