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

前端 未结 3 1742
一向
一向 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条回答
  • 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()))
    
    0 讨论(0)
  • 2020-12-09 08:15
    1. The query is correct

    2A. As far as last seven days have much less rows than whole table an index can help

    2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size

    0 讨论(0)
  • 2020-12-09 08:23

    Yes, the syntax is accurate and it should be fine.

    Here is the SQL Fiddle Demo I created for your particular case

    create table sample2
    (
        id int primary key,
        created_date date,
        data varchar(10)
      )
    
    insert into sample2 values (1,'2012-01-01','testing');
    

    And here is how to select the data

    SELECT Created_Date
    FROM sample2
    WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
    
    0 讨论(0)
提交回复
热议问题