[英]select month and year from Date of birth IN sql
i have table with DOB column ('2012-05-29 00:00:00.000') and few other fields , i need to select the data for DOB between 6 months to 6 Years. 我有带有DOB列的表格('2012-05-29 00:00:00.000')和其他几个字段,我需要选择6个月至6年之间的DOB数据。 I tried using the below SQL but this is not giving me the right data. 我尝试使用下面的SQL,但这不能提供正确的数据。 any help will be appreciated. 任何帮助将不胜感激。
select * from dbo.xyz
where ( FLOOR(DATEDIFF(MONTH, birth_date , GETDATE()) % 12) >=6
AND FLOOR(DATEDIFF(DAY, birth_date , GETDATE()) / 365.25) <= 6
)
When using dates, the advice is to use functions only on the non-column values. 使用日期时,建议仅对非列值使用函数。 In other words, modify getdate()
, not birth_date
: 换句话说,修改getdate()
,而不是birth_date
:
select *
from dbo.xyz
where birth_date between dateadd(year, -6, getdate()) and dateadd(month, -6, getdate())
This has two advantages. 这有两个优点。 First, it makes the where
clause "sargable", which means an index can be used on the comparison. 首先,它使where
子句“可保留”,这意味着可以在比较中使用索引。 More importantly, the alternative of using datediff()
doesn't quite work as expected. 更重要的是,使用datediff()
的替代方法并不像预期的那样有效。 datediff()
counts the number of calendar boundaries between two values. datediff()
计算两个值之间的日历边界数。 So, 2014-12-31 and 2015-01-01 are one day apart, one month apart, and even one year apart. 因此,2014-12-31和2015-01-01相隔一天,相隔一个月,甚至相隔一年。
Try this 尝试这个
select * from dbo.xyz
where DATEDIFF(MONTH, birth_date , GETDATE()) between 6 and 72
Here is another option that will allow indexing on birthdate. 这是另一种允许对生日进行索引的选项。
select *
from dbo.xyz
where birthdate > DATEADD(YEAR, -6, GETDATE())
and birthdate < DATEADD(MONTH, -6, GETDATE())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.