SQL Query Where Date = Today Minus 7 Days

前端 未结 7 1129
花落未央
花落未央 2020-12-18 21:47

I have a SQL table of hits to my website called ExternalHits. I track the URL as URLx and the date the page was accessed as Datex. I run this query every week to get the cou

相关标签:
7条回答
  • 2020-12-18 22:17

    You can subtract 7 from the current date with this:

    WHERE datex BETWEEN DATEADD(day, -7, GETDATE()) AND GETDATE()
    
    0 讨论(0)
  • 2020-12-18 22:19

    Using dateadd to remove a week from the current date.

    datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE()
    
    0 讨论(0)
  • 2020-12-18 22:22

    You can use the CURDATE() and DATE_SUB() functions to achieve this:

    SELECT URLX, COUNT(URLx) AS Count
    FROM ExternalHits
    WHERE datex BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()    
    GROUP BY URLx
    ORDER BY Count DESC; 
    
    0 讨论(0)
  • 2020-12-18 22:23

    Use the built in functions:

    SELECT URLX, COUNT(URLx) AS Count
    FROM ExternalHits
    WHERE datex BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
    GROUP BY URLx
    ORDER BY Count DESC; 
    
    0 讨论(0)
  • 2020-12-18 22:24
    declare @lastweek datetime
    declare @now datetime
    set @now = getdate()
    set @lastweek = dateadd(day,-7,@now)
    
    SELECT URLX, COUNT(URLx) AS Count
    FROM ExternalHits
    WHERE datex BETWEEN @lastweek AND @now
    GROUP BY URLx
    ORDER BY Count DESC; 
    
    0 讨论(0)
  • 2020-12-18 22:32

    Use the following:

    WHERE datex BETWEEN GETDATE() AND DATEADD(DAY, -7, GETDATE())

    Hope this helps.

    0 讨论(0)
提交回复
热议问题