SQL 查询其中日期 = 今天减去 7 天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42635297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 05:09:52  来源:igfitidea点击:

SQL Query Where Date = Today Minus 7 Days

sqlsql-serverdatabasebetween

提问by Ashley K

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.

我有一个名为 ExternalHits 的网站的 SQL 命中表。我将 URL 跟踪为 URLx,将访问页面的日期作为 Datex。我每周运行此查询以获取前一周的总点击次数,并且每周我都必须手动更改“之间”日期。有什么方法可以更改我的查询,以便“之间”日期类似于今天和今天-7?我只是不想每周都手动更改日期。

    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; 

回答by Aziz Javed

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; 

回答by Guillaume Mercier

Using dateadd to remove a week from the current date.

使用 dateadd 从当前日期中删除一周。

datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE()

回答by Ben

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; 

回答by kristech

You can subtract 7 from the current date with this:

您可以使用以下方法从当前日期中减去 7:

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

回答by BRogers

Use the following:

使用以下内容:

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

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

Hope this helps.

希望这可以帮助。

回答by Hunter McMillen

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

您可以使用CURDATE()DATE_SUB()函数来实现这一点:

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; 

回答by user10996728

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))