简体   繁体   English

从出生日期中选择月份和年份

[英]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.

相关问题 单个表的平均出生日期(Oracle SQL) - Avg date of birth year from single table (oracle sql) SQL 按月和年选择日期范围 - SQL select date range by month and year 在 Select 查询中创建年和月的日期 - Create a date from Year and Month on a Select query 从月份和年份SQL声明日期变量 - Declare a date variable from month and year SQL 如何从SQL中的日期获取月份和年份 - How to get month and year from date in SQL SQL Select查询以选择截止日期之间的数据,其中起始日期月份大于截止日期月份,年份差&gt; 1 - SQL Select query to select data between to dates where from date month is higher than the to date month and year difference is >1 SQL:尝试从日期中提取年份和月份 - SQL: Trying to extract year and month from a date 从 SQL DATE 获取月份和年份 - Getting only Month and Year from SQL DATE 错误 SQLiteOpenHelper: no such column: year in “SELECT event, time, date, month, year FROM eventstable WHERE month=? 和年=年” - Error SQLiteOpenHelper : no such column: year in “SELECT event, time, date, month, year FROM eventstable WHERE month=? and year=year” 在 sql server2005 中使用 sql 查询从当前日期的出生日期查找年份中的年龄? - find age in year from date of birth from current date using sql query in sql server2005?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM