Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find previous sunday date algorithm

I found a couple examples online but I don't quite understand how it works. e.g

     SELECT DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 0)

I'm not even sure it does what I want.

What I need is, when the query is executed, it can SELECT * from xTable WHERE xDate is between two dates. Last sunday and next sunday (current week). What could I use to find it automaticly? And please explain because I'm new to SQL.

like image 917
phadaphunk Avatar asked Jun 19 '12 13:06

phadaphunk


People also ask

How can I get previous Sunday date?

To get the date of the previous Sunday, use the setDate() method, setting the date to the result of subtracting the day of the week from the day of the month. The setDate method changes the day of the month of the specific Date instance. Copied!


1 Answers

I looked deeper in trying to understand this query

 SELECT DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 0)

And used it to retreive the previous monday. Now I can simply DATEADD 6 more days to get a full week.

The solution I used :

       Set @Monday =  DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 0)
       Set @Sunday =  DATEADD(dd, 06, @Monday)

Problem solved.

like image 99
phadaphunk Avatar answered Sep 28 '22 09:09

phadaphunk