简体   繁体   English

如何在查询时使用datediff函数查找年龄范围?

[英]How to use datediff function to find age range while querying?

I have a table A with date-of-birth (dd-mm-yy format) column, DOB, and suppose another table B, with data which I want to join. 我有一个表A,其中包含出生日期(dd-mm-yy格式)列,DOB,并假设另一个表B,其中包含我想要加入的数据。 How can I join considering a particular age range like 18 to 25? 如何考虑18到25岁的特定年龄范围?

This is what I have written, but it's not working: 这就是我写的,但它不起作用:

select * from B
inner join (select * from A
    where datediff(year, DOB, year(getdate())) between 18 and 25) A
on B.id = A.id

You should not use datediff() for this purpose. 你不应该为此目的使用datediff() Instead: 代替:

where dob >= dateadd(year, -25, getdate()) and
      dob <= dateadd(year, -18, getdate())

There are two important reasons why. 有两个重要原因。 First, using a function on dob prevents the use of indexes and other optimizations. 首先,在dob上使用函数可以防止使用索引和其他优化。 That can result in inferior query plans. 这可能导致较差的查询计划。

Second, datediff() measures year boundaries. 其次, datediff()测量年份边界。 So, it is actually returning people who were born in the calendar year (from Jan 1 to Dec 31) 18 to 25 years ago. 因此,它实际上是回归18至25年前出生于日历年(从1月1日到12月31日)的人。 Generally, you are not interested in calendars for this purpose. 通常,您对此日期的日历不感兴趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM