select 从出生日期开始的年月 sql

select month and year from Date of birth IN sql

我有 table 与 DOB 列 ('2012-05-29 00:00:00.000') 和其他几个字段,我需要 select DOB 的数据介于 6个月到 6 岁。我尝试使用下面的 SQL 但这没有给我正确的数据。任何帮助将不胜感激。

select * from dbo.xyz
where ( FLOOR(DATEDIFF(MONTH, birth_date , GETDATE()) % 12) >=6
      AND  FLOOR(DATEDIFF(DAY, birth_date , GETDATE()) / 365.25) <= 6
      )

试试这个

select * from dbo.xyz
where DATEDIFF(MONTH, birth_date , GETDATE()) between 6 and 72

这是另一个允许在生日上建立索引的选项。

select *
from dbo.xyz
where birthdate > DATEADD(YEAR, -6, GETDATE())
    and birthdate < DATEADD(MONTH, -6, GETDATE())

使用日期时,建议仅对非列值使用函数。也就是说,修改getdate(),而不是birth_date:

select *
from dbo.xyz
where birth_date between dateadd(year, -6,  getdate()) and dateadd(month, -6, getdate())

这有两个好处。首先,它使 where 子句成为 "sargable",这意味着可以在比较中使用索引。更重要的是,使用 datediff() 的替代方法并不像预期的那样有效。 datediff() 计算两个值之间 日历边界 的数量。所以,2014-12-31和2015-01-01相隔一天,相隔一个月,甚至相隔一年。