我的网站的命中SQL表格名为ExternalHits。我将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;