How to select last one week data from today's date

前端 未结 3 1749
一向
一向 2020-12-09 07:50

How to select week data (more precisely, last 7 days data) from the current date in the fastest way as I have millions or rows in the table. I have a time stamp of created_d

3条回答
  •  -上瘾入骨i
    2020-12-09 08:15

    to select records for the last 7 days

    WHERE Created_Date >= DATEADD(day, -7, GETDATE())
    

    to select records for the current week

    SET DATEFIRST 1 -- Define beginning of week as Monday
    SELECT * FROM
    WHERE CreatedDate >= DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE())) 
      AND CreatedDate <  DATEADD(day, 8 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))
    

    if you want to select records for last week instead of the last 7 days

    SET DATEFIRST 1 -- Define beginning of week as Monday
    SELECT * FROM  
    WHERE CreatedDate >= DATEADD(day, -(DATEPART(dw, GETDATE()) + 6), CONVERT(DATE, GETDATE())) 
      AND CreatedDate <  DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))
    

提交回复
热议问题