I have 2 columns named Userid and holidaydate in a table named userdays. Below is the data.
| Userid | holidaydate |
| ------------ | ------------ |
| 1 | 2023-01-17 |
| 1 | 2023-03-21 |
| 1 | 2023-03-22 |
| 1 | 2023-03-23 |
| 1 | 2023-05-12 |
| 2 | 2023-09-15 |
| 3 | 2023-06-09 |
| 3 | 2023-06-28 |
For each user, we have to find next working day. For 2023-01-17 next work date is 2023-01-18. For 2023-03-21 next work date is 2023-03-24 because 2023-03-22 and 2023-03-23 is a holiday
I need a sql query for below output:
| Userid | nextworkdate |
| ------------ | ------------ |
| 1 | 2023-01-18 |
| 1 | 2023-03-24 |
| 1 | 2023-03-24 |
| 1 | 2023-03-24 |
| 1 | 2023-05-13 |
| 2 | 2023-09-16 |
| 3 | 2023-06-10 |
| 3 | 2023-06-29 |
3条答案
按热度按时间bjp0bcyl1#
You could do a window function solution to get the next workday:
First you check if next non-holiday is same as next day, if not that's the value we want, otherwise we go to the next step.
In the next step, we get the first non-holiday date that we previously calculated in a "following" window function, ie. we basically look ahead and take the first non-holiday date from the table.
0ve6wy6x2#
If weekends and business holidays don't interest you, this might be helpful :
Explanations :
C1 retrieves the
nextdate
by adding 1 day to theholidaydate
.C2 retrieves potential
nextworkdate
by excluding holidays.Results :
Demo here
kxeu7u2r3#
Try this