How to select data from 30 days?

你离开我真会死。 提交于 2019-12-03 06:28:36

问题


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


回答1:


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



回答2:


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

SELECT DATEADD(DAY,-30,GETDATE())



回答3:


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




回答4:


Short version for easy use:

SELECT * 
FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())

DATEADD and GETDATE are available in SQL Server starting with 2008 version. MSDN documentation: GETDATE and DATEADD.



来源:https://stackoverflow.com/questions/16645973/how-to-select-data-from-30-days

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!