13

I want to find record by this week just declare current date. Example:

     select datename(dw,getdate())  -- Example today is Friday "27-04-2012"

so how can i get date range

     start on monday "23-04-2012" or sunday "22-04-2012"  As @dateStart to

     end on sunday "29-04-2012"  or saturday "28-04-2012" As @dateEnd

then i can select query by

     select * from table where date>=@dateStart  AND date<=@dateEnd
user983738
  • 993
  • 3
  • 13
  • 27
  • You need to test for which day of the week you're on and subtract/add the relevant number of days to your date. – BugFinder Apr 27 '12 at 10:54

3 Answers3

21

Here are some helpful commands to get each day of the week

SELECT 
    DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -2) SatOfPreviousWeek,
    DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -1) SunOfCurrentWeek,
    DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0) MondayOfCurrentWeek,
    DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 1) TuesOfCurrentWeek,
    DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 2) WedOfCurrentWeek,
    DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 3) ThursOfCurrentWeek,
    DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 4) FriOfCurrentWeek,
    DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 5) SatOfCurrentWeek

you would then use these in your query to get the date range:

SELECT *
FROM yourTable
WHERE yourDate >= DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -1) -- Sunday
AND yourDate <= DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 5) -- Saturday
Taryn
  • 242,637
  • 56
  • 362
  • 405
5

So you want only records from this week?

SELECT t.* 
FROM table t 
WHERE t.date >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) / 7 * 7, 0)
AND   t.date <= DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()), 0)
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

The queries that others have suggested may work, but you haven't defined what a "week" is for you. Depending on the country/region and the business reasons, a week could be Sun-Sat, Mon-Sun, Mon-Fri etc.

Therefore the best solution for finding the first and last days of the week is probably a calendar table where you pre-populate the first and last days of the week for every date that you'll need. Then you can use a simple query to get the correct start and end dates to use in your query:

select @StartDate = FirstDayOfWeek, @EndDate = LastDayOfWeek
from dbo.Calendar
where BaseDate = @SomeDate

This solution also has the advantage that you can easily work with different definitions of a week by adding new columns to your calendar table.

Community
  • 1
  • 1
Pondlife
  • 15,992
  • 6
  • 37
  • 51