I have two tables as below
emp_id | start_date | End Date
------------------------------------------
1 | May-10-2017 | May-30-2017
1 | Jun-05-2017 | null
2 | May-08-2017 | null
emp_id | start_date | End Date | Rate
-----------------------------------------------
1 | May-20-2017 | Jun-30-2017 | 75
1 | Jul-01-2017 | null | 80
These 2 tables share the emp_id (employee id) foreign key and joining these two I should be able to:
I am able to achieve the first part of result using the join query below
select distinct emp_id from work_contracts
left join hourly_pay hr USING(emp_id)
where hr.emp_id is null
I am stuck on the second part where probably I need a correlated subquery to tell the hourly pay table records that did not start before the work_assignments start_date? or is there any other way?
To get all of the rows from just one of the tables – the matched rows as well as the unmatched rows – you need to use the LEFT JOIN or the RIGHT JOIN .
Compare Two Tables using UNION ALLSelect * from ( Select Id_pk, col1, col2...,coln from table1, 'Old_table' Union all Select Id_pk, col1, col2...,coln from table2, 'New_tbale' ) cmpr order by Id_pk; The above query returns the all rows from both tables as old and new.
Do the date comparison in an inner query then wrap it to filter it to the ones that satisfy the late pay criteria.
select * from (
select distinct c.emp_id,
case when c.start_date < hr.start_date then 1 else 0 end as latePay
from work_contracts c
left join hourly_pay hr USING(emp_id)
) result
where latePay = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With