如何从今天的SQL服务器日期获取最近30天的数据 [英] How to get last 30 days data from today's date in SQL server

查看:677
本文介绍了如何从今天的SQL服务器日期获取最近30天的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须记录从过去30天到今天的所有行。我试过这个但是没有工作



我尝试过:



从dsr_data中选择date_time,其中date_time> = CONVERT(Varchar(100),DATEADD(DAY,-30,GETDATE()),103)和date_time< = CONVERT(varchar(100),getdate(),103 )

解决方案

你为什么使用CONVERT?

唯一可能的原因是它不起作用的原因相同:你存储你的将日期作为NVARCHAR列而不是DATE,DATETIME或DATETIME2。



比较字符串时,比较完全基于两个字符串中的第一个不同字符:和因为你专门选择以103格式格式化日期,即dd / MM / yyyy比较将是总垃圾 - 例如,最后一年将检查年份,所以31/01/2017将在31/12之前/ 1952因为比较将基于月份的第一个数字,'0'小于'1'



更改y数据库。始终以适当的数据类型存储数据:这意味着INT列中的整数值,DATE,DATETIME或DATETIME2列中的日期信息,等等。如果你不这样做,这只是许多令人讨厌的令人讨厌的问题中的第一个,等着咬你的话......


使用下面的查询。



 SELECT date_time FROM dsr_data 
WHERE date_time> = DATEADD(day,-30,getdate())
和date_time< = getdate()


 SELECT date_time FROM dsr_data 
WHATE date_time
介于DATEADD之间(DAY,-30,GETDATE())和GETDATE();


i have to get record of all rows from last 30 to todays. i have tried this but isn't working

What I have tried:

select date_time from dsr_data where date_time >= CONVERT(Varchar(100), DATEADD(DAY,-30,GETDATE()),103) and date_time <= CONVERT(varchar(100), getdate(),103)

解决方案

Why are you using CONVERT?
The only possible reason is the same reason it doesn't work: you are storing your dates as NVARCHAR columns instead of DATE, DATETIME, or DATETIME2.

When you compare strings, the comparison is based entirely on the first different character in the two strings: and since you are specifically selecting to format the date in 103 format, which is "dd/MM/yyyy" the comparison will be total junk - the year will be checked last for example, so 31/01/2017 will be before 31/12/1952 because the comparison will be based on the first digit on the month, and '0' is less than '1'

Change your database. Always store data in appropriate datatypes: that means integer values in INT columns, date information in DATE, DATETIME, or DATETIME2 columns, and so on. If you don't, this is just the first of many nasty, nasty problems waiting to bite you down the line...


Use below query.

SELECT date_time  FROM  dsr_data
WHERE date_time  >= DATEADD(day,-30, getdate()) 
and   date_time  <= getdate()


SELECT date_time  FROM dsr_data
    WHERE date_time
               between DATEADD(DAY,-30,GETDATE()) and  GETDATE(); 


这篇关于如何从今天的SQL服务器日期获取最近30天的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆