Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query Where Date = Today Minus 7 Days

Tags:

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;  
like image 419
Ashley K Avatar asked Mar 06 '17 20:03

Ashley K


People also ask

How do I add 7 days to a date in SQL?

SQL Server DATEADD() Function The DATEADD() function adds a time/date interval to a date and then returns the date.

How can I use today date in SQL query?

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 .

Can you subtract from a date in SQL?

SQL Server DATEDIFF() FunctionThe DATEDIFF() function returns the difference between two dates.


2 Answers

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;  
like image 133
azizj Avatar answered Sep 25 '22 08:09

azizj


Using dateadd to remove a week from the current date.

datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE() 
like image 35
Guillaume Mercier Avatar answered Sep 25 '22 08:09

Guillaume Mercier