Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous Tuesday (or any given day of week) for specified date

I want to get previous Tuesday (or any given day of week) for specified date. Here is the sample input and expected output for Tuesday:

CREATE TABLE #temp(testdate DATETIME);
INSERT INTO  #temp(testdate) VALUES
    ('2015-10-06 01:15'), -- Tue -> Tue 2015-10-06 00:00
    ('2015-10-07 04:30'), -- Wed -> Tue 2015-10-06 00:00
    ('2015-10-08 00:30'), -- Thu -> Tue 2015-10-06 00:00
    ('2015-10-09 21:00'), -- Fri -> Tue 2015-10-06 00:00
    ('2015-10-10 19:00'), -- Sat -> Tue 2015-10-06 00:00
    ('2015-10-11 01:15'), -- Sun -> Tue 2015-10-06 00:00
    ('2015-10-12 13:00'), -- Mon -> Tue 2015-10-06 00:00

    ('2015-10-13 18:45'), -- Tue -> Tue 2015-10-13 00:00
    ('2015-10-14 12:15'), -- Wed -> Tue 2015-10-13 00:00
    ('2015-10-15 10:45'), -- Thu -> Tue 2015-10-13 00:00
    ('2015-10-16 04:30'), -- Fri -> Tue 2015-10-13 00:00
    ('2015-10-17 12:15'), -- Sat -> Tue 2015-10-13 00:00
    ('2015-10-18 00:30'), -- Sun -> Tue 2015-10-13 00:00
    ('2015-10-19 10:45'), -- Mon -> Tue 2015-10-13 00:00

    ('2015-10-20 01:15'), -- Tue -> Tue 2015-10-20 00:00
    ('2015-10-21 23:45'), -- Wed -> Tue 2015-10-20 00:00
    ('2015-10-22 21:00'), -- Thu -> Tue 2015-10-20 00:00
    ('2015-10-23 18:45'), -- Fri -> Tue 2015-10-20 00:00
    ('2015-10-24 06:45'), -- Sat -> Tue 2015-10-20 00:00
    ('2015-10-25 06:45'), -- Sun -> Tue 2015-10-20 00:00
    ('2015-10-26 04:30'); -- Mon -> Tue 2015-10-20 00:00

DECLARE @clampday AS INT = 3; -- Tuesday
SELECT -- DATEADD/DATEPART/@clampday/???

What is the most appropriate way to get the previous Tuesday (or any day of week) using T-SQL?

like image 420
Salman A Avatar asked Oct 12 '15 11:10

Salman A


People also ask

How do I extract the day of the week from a date in SQL?

MySQL WEEKDAY() Function The WEEKDAY() function returns the weekday number for a given date. Note: 0 = Monday, 1 = Tuesday, 2 = Wednesday, 3 = Thursday, 4 = Friday, 5 = Saturday, 6 = Sunday.

How do I get the day of the week to start in SQL?

In SQL Server, there is a @@DATEFIRST function, which returns the current week start day (value of SET DATEFIRST).


1 Answers

i hope this will help you

SELECT DATEADD(day,- (DATEPART(dw, testdate) + @@DATEFIRST - 3) % 7,testdate) AS Saturday  
from #temp

OR

SELECT DATENAME(weekday,DATEADD(day,- (DATEPART(dw, testdate) + @@DATEFIRST - 3) % 7,testdate)) +'  '+ 
        CONVERT(nvarchar,DATEADD(day,- (DATEPART(dw, testdate) + @@DATEFIRST - 3) % 7,testdate),101) AS Saturday
from @temp

OUTPUT would be in below formate

Saturday
Tuesday  10/06/2015

Remark: the whole query is just combination and calculation of DATEFIRST, DATEPART and DATEADD to manipulate a time

like image 108
wiretext Avatar answered Nov 13 '22 20:11

wiretext