I'm working on a query but it's returning some duplicate values and I need to return only the row where the date in one column is closest to the date in another column.
My query looks something like this:
SELECT p.Id, r.ReferralDate, s.SupervisionDate
FROM person p
INNER JOIN referral r on r.PersonId = p.Id
INNER JOIN supervision s on s.PersonId = p.Id
Which returns something like this:
| Id | Supervision Date | Referral Date |
|---|---|---|
| 123 | 2015-09-30 | 2015-08-30 |
| 123 | 2020-02-30 | 2015-08-30 |
| 123 | 2020-06-30 | 2015-08-30 |
| 456 | 2010-06-30 | 2010-07-30 |
| 456 | 2005-06-30 | 2010-07-30 |
How can I write a query that returns the Supervision Date that is closest to the Referral Date? So that the final output looks like this:
| Id | Supervision Date | Referral Date |
|---|---|---|
| 123 | 2015-09-30 | 2015-08-30 |
| 456 | 2010-06-30 | 2010-07-30 |

