Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: how to get sunday of current week

I want to get the last day( Sunday) of current week given any timestamp. I tried following script, but it returns Saturday as the last day rather than Sunday as I expected.

Select DATEADD(DAY , 7-DATEPART(WEEKDAY,GETDATE()),GETDATE()) AS 'Last Day Of Week' 

Any answer is welcomed!!

like image 998
Echo Avatar asked Jul 20 '12 13:07

Echo


People also ask

Where can I find Sunday in SQL query?

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 Sunday Monday from date in SQL?

SQL Server has a couple of inbuilt functions to get the day of week from the given date. To get the name of the day of week, you can use DATENAME function and to get the number of the day of week, you can use DATEPART function.


2 Answers

It will work if you change the standard DATEFIRST from Sunday (7) to Monday (1):

SET DATEFIRST 1

Select DATEADD(DAY , 7-DATEPART(WEEKDAY,GETDATE()),GETDATE()) AS 'Last Day Of Week' 
like image 139
Aaron Bertrand Avatar answered Sep 22 '22 09:09

Aaron Bertrand


DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 6)

I know this post is old but this post comes at the top when searched through via Google.

Always good to be updating.

like image 36
Jona Avatar answered Sep 20 '22 09:09

Jona