Get Last Week’s Records with T-SQL


You can use DATEADD and DATEDIFF functions to get the start time of a particular week from your current date.

You can compare your datetime column value with the start time of the week and retrieve all records within the range.

Here is the code snippet:

SELECT DATEADD(week, DATEDIFF(week,0,GETDATE())-1,-1) BeginningOfLastWeek,

DATEADD(week, DATEDIFF(week,0,GETDATE()),-1) BeginningOfThisWeek,

DATEADD(week, DATEDIFF(week,0,GETDATE())+1,-1) BeginningOfNextWeek

 

Last week’s data

 

…WHERE mydate >= DATEADD(week, DATEDIFF(week,0,GETDATE())-1,-1)

AND mydate < DATEADD(week, DATEDIFF(week,0,GETDATE()),-1)

 

This week’s data

…WHERE mydate >= DATEADD(week, DATEDIFF(week,0,GETDATE()),-1)

AND mydate < DATEADD(week, DATEDIFF(week,0,GETDATE())+1,-1)

 

Get this Sunday or Monday and last Sunday or Monday:

—Start from last Monday
SELECT DATEADD(WEEK, DATEDIFF(WEEK, ‘1900-01-01’, CURRENT_TIMESTAMP)-1, ‘1900-01-01’)
—Start from this Monday
SELECT DATEADD(WEEK, DATEDIFF(WEEK, ‘1900-01-01’, CURRENT_TIMESTAMP), ‘1900-01-01’)
—Start from Sunday
SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP ), Cast(CURRENT_TIMESTAMP as date))
—Start from last Sunday
SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP )-7, Cast(CURRENT_TIMESTAMP as date))

Advertisements

2 Comments on “Get Last Week’s Records with T-SQL”

  1. Denise says:

    Thank you for giving this clean example of last full week!

  2. […] Get Last Week’s Records with T-SQL | Jingyang Li – Aug 02, 2012  · Get Last Week’s Records with T-SQL … Last week’s data … number data in varchar column that are imported from Excel in SQL Server; […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s