Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select data from 30 days?

I have query:

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)
) x
GROUP BY name ORDER BY name

But DATE_SUB is a MySQL function and I need function for MsSQL 2008

Tell me please how to select data from 30 days by using MsSQL 2008?

P.S.: Data type of datetime is smalldatetime

like image 459
Alex N Avatar asked May 20 '13 09:05

Alex N


People also ask

How do I get 30 days old data in SQL?

SELECT * FROM product WHERE pdate >= DATEADD(day, -30, getdate()).

How do I choose data for a month?

To select all entries from a particular month in MySQL, use the monthname() or month() function. The syntax is as follows. Insert some records in the table using insert command. Display all records from the table using select statement.


3 Answers

You should be using DATEADD is Sql server so if try this simple select you will see the affect

Select DATEADD(Month, -1, getdate())

Result

2013-04-20 14:08:07.177

in your case try this query

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name
like image 127
Raab Avatar answered Oct 18 '22 21:10

Raab


Try this : Using this you can select date by last 30 days,

SELECT DATEADD(DAY,-30,GETDATE())
like image 24
Anvesh Avatar answered Oct 18 '22 20:10

Anvesh


For those who could not get DATEADD to work, try this instead: ( NOW( ) - INTERVAL 1 MONTH )

like image 14
maikelsabido Avatar answered Oct 18 '22 20:10

maikelsabido