I am using this query to get last previsous date.
SELECT *
FROM MyTable
WHERE
CAST(MyTable.DATE AS DATE) = DATEADD(day, -1, CAST(GETDATE() AS date))
I want to exclude weekends and from today should give yesterday, or on Monday, will give the previous Friday
CodePudding user response:
You could check for today being 'Monday' and subtract 3 days, otherwise subtract 1:
SELECT DATEADD(
day,
IIF(DATENAME(weekday, GETDATE()) = 'Monday', -3, -1),
CAST(GETDATE() AS DATE)
)
CodePudding user response:
This is easy to solve with a calendar table, and doesn't rely on @@language
or @@datefirst
settings:
DECLARE @PreviousWeekday date;
SELECT @PreviousWeekday = MAX(TheDate)
FROM dbo.TheCalendar
WHERE IsWeekend = 0
AND TheDate >= DATEADD(DAY, -4, GETDATE());
SELECT <column_list>
FROM dbo.MyTable
WHERE [DATE] >= @PreviousWeekday
AND [DATE] < DATEADD(DAY, 1, @PreviousWeekday);
As a bonus, that where clause can use an index on [DATE]
with the right estimates, and the calendar table makes it easy to adjust later if you decide you want to skip holidays or other work outages that are technically weekdays but not work days (just add AND IsHoliday = 0)
.
Further reading:
- Why you should have a calendar table (and also use cases)
- Why casting a column to date is not a great idea, and why an open-ended range is best
- Why you should always use the schema prefix
- Why you should never use
SELECT *