How to select data from 30 days?

Alex N picture Alex N · May 20, 2013 · Viewed 110.7k times · Source

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

Answer

Raab picture Raab · May 20, 2013

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