在SQL Server中计算年龄范围

时间:2018-06-27 22:21:31

标签: sql sql-server

我正在尝试生成仅显示65岁及以上客户的报告。我想知道SQL的months_between是什么,以及如何正确地将报告限制为65岁以上的客户。我已在下面附上我的声明。任何帮助表示赞赏。谢谢。

 SELECT person.idFamily AS Family_ID, person.id AS Person_ID,(SELECT person.firstName+ ', ' + person.lastName) AS Name, person.Race AS Race, person.Ethnicity as Ethnicity, family.capidCounty AS County, Person.BirthDate AS [DateofBirth], trunc(months_between(sysdate,DateofBirth)/12))AS Age
FROM Family
LEFT JOIN person ON family.Id = person.idFamily

2 个答案:

答案 0 :(得分:0)

这应该可以吸引65岁以上的人及其年龄。 DATEDIFF计算两个日期之间的差,DATEADD可以从日期中进行加/减。

select *, DATEDIFF(year,BirthDate,getdate()) as Age from Person where BirthDate < DATEADD(year, -65, getdate())

有关DATEDIFFDATEADD

的更多信息

答案 1 :(得分:0)

在SQL Server中应该可以执行以下操作:

SELECT p.idFamily AS Family_ID, p.id AS Person_ID,
       (p.firstName + ', ' + p.lastName) AS Name, p.Race AS Race, p.Ethnicity as Ethnicity,
       f.capidCounty AS County, p.BirthDate AS [DateofBirth], 
       datediff(month, dateofbirth, getdate()) / 12 as age
FROM Family f LEFT JOIN
     person p
     ON f.Id = p.idFamily;

这不是精确匹配,但逻辑可能足够好。请注意,年龄将在带有生日的月份的第一个月的第一天增加。