Always return data from last week's Monday thru Sunday

前端 未结 4 645
时光说笑
时光说笑 2021-01-13 19:34

How to write a sql statement that always returns data from last Monday to the last Sunday? Any guidance is appreciated.

Thanks.

4条回答
  •  没有蜡笔的小新
    2021-01-13 20:08

    I realized my code was too complex, so I changed my answer to this. The minus one after getdate() corrects this to return the last Monday on Sunday instead of this weeks Monday (tomorrow if today is Sunday).

    SELECT t.* 
    FROM  t CROSS JOIN
    (SELECT DATEDIFF(week, 0, getdate() - 1) * 7 lastmonday) a
    WHERE t.yourdate >= a.lastmonday - 7 and yourdate < a.lastmonday
    

    Old code

    SELECT t.* 
    FROM 
    t CROSS JOIN (SELECT DATEDIFF(day, 0, getdate() - DATEDIFF(day, 0, getdate()) %7) lastmonday) a WHERE t.yourdate >= a.lastmonday - 7 and yourdate < a.lastmonday

    提交回复
    热议问题