SQL Query Where Date = Today Minus 7 Days

2019-02-18 18:10发布

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 count of total hits from the week before, and every week I have to manually change the "between" dates. Is there some way I can change my query so that the "between" dates are something like TODAY AND TODAY-7? Ijust want to not have to manually change the dates every week.

    SELECT URLX, COUNT(URLx) AS Count
    FROM ExternalHits
    WHERE datex BETWEEN '02/27/2017' AND '03/05/2017'    
    GROUP BY URLx
    ORDER BY Count DESC; 

7条回答
Emotional °昔
2楼-- · 2019-02-18 18:23

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; 
查看更多
Viruses.
3楼-- · 2019-02-18 18:32
DECLARE @Daysforward int
SELECT @Daysforward = 25 (no of days required)
Select * from table name

where CAST( columnDate AS date) < DATEADD(day,1+@Daysforward,CAST(GETDATE() AS date))
查看更多
放荡不羁爱自由
4楼-- · 2019-02-18 18:33

You can subtract 7 from the current date with this:

WHERE datex BETWEEN DATEADD(day, -7, GETDATE()) AND GETDATE()
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-02-18 18:35

Using dateadd to remove a week from the current date.

datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE()
查看更多
闹够了就滚
6楼-- · 2019-02-18 18:35

Use the following:

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

Hope this helps.

查看更多
孤傲高冷的网名
7楼-- · 2019-02-18 18:38
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; 
查看更多
登录 后发表回答