我的网站有一个名为“ExternalHits”的 SQL 命中表。我将 URL 跟踪为 URLx,并将访问页面的日期跟踪为 Datex。我每周运行此查询以获取前一周的总点击数,并且每周我都必须手动更改“之间”日期。有什么方法可以更改我的查询,以便“之间”日期类似于 TODAY AND TODAY-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;
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;
使用 dateadd 从当前日期中删除一周。
datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE()
您可以用以下方法从当前日期中减去 7:
WHERE datex BETWEEN DATEADD(day, -7, GETDATE()) AND GETDATE()
使用内置函数:
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;
使用以下内容:
WHERE datex BETWEEN GETDATE() AND DATEADD(DAY, -7, GETDATE())
希望这有帮助。
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;
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))
对于 MariaDB:
WHERE datex BETWEEN DATE_ADD(CURDATE(), INTERVAL -7 DAY) AND CURDATE()
它对我有帮助。
纯Mysql:
WHERE datex BETWEEN adddate(curdate(), -7)) AND curdate();