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;
SQL Server DATEADD() Function The DATEADD() function adds a time/date interval to a date and then returns the date.
To get the current date and time in SQL Server, use the GETDATE() function. This function returns a datetime data type; in other words, it contains both the date and the time, e.g. 2019-08-20 10:22:34 .
SQL Server DATEDIFF() FunctionThe DATEDIFF() function returns the difference between two dates.
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;
Using dateadd to remove a week from the current date.
datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With