How to get last day of last week in sql?

Regardless of the actual DATEFIRST setting, the last Sunday could be found like this:

SELECT DATEADD(day,
               -1 - (DATEPART(weekday, GETDATE()) + @@DATEFIRST - 2) % 7,
               GETDATE()
              ) AS LastSunday

Replace GETDATE() with a parameter @date to get the last Sunday before a particular date.


Last Sunday (Which is the end of "last week")

SELECT DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6) AS LAST_SUNDAY

This Week (Assuming Mon-Sun Week Format)

SELECT DATEADD(wk, DATEDIFF(wk, 7, CURRENT_TIMESTAMP), 7) AS START_OF_WEEK
SELECT DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6 + 7) AS END_OF_WEEK

Results

START_OF_WEEK
-----------------------
2011-05-02 00:00:00.000

END_OF_WEEK
-----------------------
2011-05-08 00:00:00.000

Examples to explain the voodoo (Use this to change above SQL to your desired Week Starting and Week Ending day-of-week)

  • The examples below locate days of the week within the current week (Sunday to Saturday)
  • If the actual END_OF_WEEK is next Sun-Sat week, then you need to +7 to this week's value. (See the END_OF_WEEK example above.)

SQL Below

SELECT DATEADD(wk, DATEDIFF(wk, -2, CURRENT_TIMESTAMP), -2) AS DAY_OF_WEEK /* Saturday */
SELECT DATEADD(wk, DATEDIFF(wk, -1, CURRENT_TIMESTAMP), -1) AS DAY_OF_WEEK /* Sunday */
SELECT DATEADD(wk, DATEDIFF(wk, 0, CURRENT_TIMESTAMP), 0) AS DAY_OF_WEEK /* Monday */
SELECT DATEADD(wk, DATEDIFF(wk, 1, CURRENT_TIMESTAMP), 1) AS DAY_OF_WEEK /* Tuesday */
SELECT DATEADD(wk, DATEDIFF(wk, 2, CURRENT_TIMESTAMP), 2) AS DAY_OF_WEEK /* Wednesday */
SELECT DATEADD(wk, DATEDIFF(wk, 3, CURRENT_TIMESTAMP), 3) AS DAY_OF_WEEK /* Thursday */
SELECT DATEADD(wk, DATEDIFF(wk, 4, CURRENT_TIMESTAMP), 4) AS DAY_OF_WEEK /* Friday */
SELECT DATEADD(wk, DATEDIFF(wk, 5, CURRENT_TIMESTAMP), 5) AS DAY_OF_WEEK /* Saturday */
SELECT DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6) AS DAY_OF_WEEK /* Sunday */
SELECT DATEADD(wk, DATEDIFF(wk, 7, CURRENT_TIMESTAMP), 7) AS DAY_OF_WEEK /* Monday */
SELECT DATEADD(wk, DATEDIFF(wk, 8, CURRENT_TIMESTAMP), 8) AS DAY_OF_WEEK /* Tuesday */
SELECT DATEADD(wk, DATEDIFF(wk, 9, CURRENT_TIMESTAMP), 9) AS DAY_OF_WEEK /* Wednesday */
SELECT DATEADD(wk, DATEDIFF(wk, 10, CURRENT_TIMESTAMP), 10) AS DAY_OF_WEEK /* Thursday */
SELECT DATEADD(wk, DATEDIFF(wk, 11, CURRENT_TIMESTAMP), 11) AS DAY_OF_WEEK /* Friday */
SELECT DATEADD(wk, DATEDIFF(wk, 12, CURRENT_TIMESTAMP), 12) AS DAY_OF_WEEK /* Saturday */
etc...