Skip to content
Advertisement

DATEPART fix days

I set datefirst 1 but i can’t how to improve this. I’m sorry for less information. I’m using SQL Server. I uploaded the .img to exemplify.

CASE WHEN DAY % 2 = 0 AND POL = 'SUUA' THEN CONVERT(VARCHAR(15),DATEPART(DAY,5)) + ' TO ' + CONVERT(VARCHAR(15),DATEPART(DAY,3),103)

I want to show somwthing like this

Advertisement

Answer

I highly recommend using a Calendar Table for this. A calendar table holds date values with additional information, so it’s easier to find particular days (like business days or weekdays, as for this example).

The following solution uses a calendar table and 2 CROSS APPLY operators to get the previous collection dates.

This is how you can create a calendar table (recursive CTE):

The table is like the following:

We will use this to find the closest Wednesday and Monday just before a particular Departure date. We find this using a CROSS APPLY having the DepartureDate as a higher limit, then searching for the particular weekday (1 for monday, 3 for wednesday). Then use TOP 1 with ORDER BY Date DESC to get the highest Monday/Wednesday just before that departure date.

Finding the previous Friday from a Wednesday is as simple as moving backwards 5 days, the same goes from Monday to Wednesday.

Results:

This was a good SQL exercise.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement