Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select last 30 days with a sql query

I am looking for the number of Mon,Tues, Wed, Thur, Fri, Sat, Sun in the past 30 days. Can I select the last 30 days date and day of week without an actual database table? Something like

SELECT --everything between
convert(date,GETDATE()), DATENAME(DW, GETDATE())
--and
convert(date,GETDATE() - 30), DATENAME(DW, GETDATE())
like image 384
MrM Avatar asked May 12 '11 17:05

MrM


3 Answers

You can use a recursive CTE:

;WITH CTE AS
(
    SELECT convert(date,GETDATE()) sDate, DATENAME(DW, GETDATE()) sDayofWeek
    UNION ALL
    SELECT DATEADD(DAY,-1,sDate), DATENAME(DW, DATEADD(DAY,-1,sDate))
    FROM CTE
    WHERE sDate > GETDATE()-29
)
SELECT * FROM CTE
like image 156
Lamak Avatar answered Oct 05 '22 22:10

Lamak


WITH cteCount AS (
    SELECT DATENAME(dw, GETDATE()) dw, 1 ix 
    UNION ALL 
    SELECT DATENAME(dw, DATEADD(d, -ix, GETDATE())), ix+1 FROM cteCount WHERE ix<30
)
SELECT dw, COUNT(1) cnt FROM cteCount GROUP BY dw
like image 31
Lucero Avatar answered Oct 05 '22 22:10

Lucero


A couple solutions:

SELECT ... From ... WHERE date > DATEADD(year, -1, GETDATE())

Also, I think this statement will work with MySQL:

select date_sub(now(),interval 30 day)as Datebefore30days;
like image 33
Kyle Avatar answered Oct 05 '22 23:10

Kyle