I am given two tables. Table 1 contains a list of appointment entries and Table 2 contains a list of date ranges, where each date range has an acceptable number of appointments it can be matched with.
I need to match an appointment from table 1 (starting with an appointment with the lowest date) to a date range in table 2. Once we've matched N appointments (where N = Allowed Appointments), we can no longer consider that date range.
Moreover, once we've matched an appointment from table 1 we can no longer consider that appointment for other matches.
Based on the matches I return table 3, with a bit column telling me if there was a match.
I am able to successfully perform this using a cursor, however this solution is not scaling well with larger datasets. I tried to match top n groups using row_count() however, this allows the same appointment to be matched multiple times which is not what I'm looking for.
Would anyone have suggestions in how to perform this matching using a set based approach?
Table 1
| ApptID | ApptDate |
|---|---|
| 1 | 01-01-2022 |
| 2 | 01-04-2022 |
| 3 | 01-05-2022 |
| 4 | 01-20-2022 |
| 5 | 01-21-2022 |
Table 2
| DateRangeId | Date From | Date To | Allowed Num Appointments |
|---|---|---|---|
| 1 | 01-01-2020 | 01-05-2020 | 2 |
| 2 | 01-06-2020 | 01-11-2020 | 1 |
| 3 | 01-12-2020 | 01-18-2020 | 2 |
| 4 | 01-20-2020 | 01-25-2020 | 1 |
| 5 | 01-20-2020 | 01-26-2020 | 1 |
Table 3 (Expected Output):
| ApptID | ApptDate | Matched | DateRangeId |
|---|---|---|---|
| 1 | 01-01-2022 | 1 | 1 |
| 2 | 01-04-2022 | 1 | 1 |
| 3 | 01-05-2022 | 0 | NULL |
| 4 | 01-20-2022 | 1 | 4 |
| 5 | 01-21-2022 | 1 | 5 |