I have 2 Tables (History and Responsible). They need to be JOINED based on Service Date.
History Table:
| Id | ServiceDate | Hours | ClientId | ClientName |
|---|---|---|---|---|
| 1 | 2021-10-15 | 3 | 123 | Tom Holland |
| 2 | 2021-10-25 | 5 | 123 | Tom Holland |
| 3 | 2022-01-14 | 2 | 123 | Tom Holland |
Responsible Table:
2999-12-31 means Responsible has no end date (current)
| ClientId | ClientName | ResponsibleId | ResponsibleName | ResponsibleStartDate | ResponsibleEndtDate |
|---|---|---|---|---|---|
| 123 | Tom Holland | 77 | Thomas Anderson | 2020-09-17 | 2021-10-17 |
| 123 | Tom Holland | 88 | Tom Cruise | 2021-10-18 | 2999-12-31 |
| 123 | Tom Holland | 99 | Sten Lee | 2022-01-07 | 2999-12-31 |
My code produces multiple rows, because 2022-01-14 Service date falls under multiple date ranges from Responsible Table:
SELECT h.Id,
h.ServiceDate,
h.Hours,
h.ClientId,
h.ClientName,
r.ResponsibleName
FROM History AS h
LEFT JOIN Responsible AS r
ON (h.ClientId = r.ClientId AND h.ServiceDate BETWEEN r.ResponsibleStartDate AND r.ResponsibleEndtDate)
The output of the query above is:
| Id | ServiceDate | Hours | ClientId | ClientName | ResponsibleName |
|---|---|---|---|---|---|
| 1 | 2021-10-15 | 3 | 123 | Tom Holland | Thomas Anderson |
| 2 | 2021-10-25 | 5 | 123 | Tom Holland | Tom Cruise |
| 3 | 2022-01-14 | 2 | 123 | Tom Holland | Tom Cruise |
| 3 | 2022-01-14 | 2 | 123 | Tom Holland | Sten Lee |
Technically, output is correct (because 2022-01-14 is between 2021-10-18 - 2999-12-31 as well between 2022-01-07 - 2999-12-31), but not what I need.
I would like to know if possible to achieve 2 outputs:
1) If Service Date falls in multiple date ranges from Responsible Table, Responsible Should be the person who's ResponsibleStartDate is closer to the ServiceDate:
| Id | ServiceDate | Hours | ClientId | ClientName | ResponsibleName |
|---|---|---|---|---|---|
| 1 | 2021-10-15 | 3 | 123 | Tom Holland | Thomas Anderson |
| 2 | 2021-10-25 | 5 | 123 | Tom Holland | Tom Cruise |
| 3 | 2022-01-14 | 2 | 123 | Tom Holland | Sten Lee |
2) Keep all rows, if Service Date falls in multiple date ranges from Responsible Table, but split Hours evenly between Responsible:
| Id | ServiceDate | Hours | ClientId | ClientName | ResponsibleName |
|---|---|---|---|---|---|
| 1 | 2021-10-15 | 3 | 123 | Tom Holland | Thomas Anderson |
| 2 | 2021-10-25 | 5 | 123 | Tom Holland | Tom Cruise |
| 3 | 2022-01-14 | 1 | 123 | Tom Holland | Tom Cruise |
| 3 | 2022-01-14 | 1 | 123 | Tom Holland | Sten Lee |