DateDiff缺少几条记录

时间:2011-09-26 22:00:07

标签: tsql datediff

我正在使用datediff函数

SELECT stName
       ,stId
       ,stDob  --(varchar(15))
       ,stJoinDt --(datetime)
FROM student stu
WHERE
DATEDIFF(yy,stu.stDob,stu.stJoinDt) between 18 and 75

由于between运算符无效,我还将代码更改为

SELECT stName
           ,stId
           ,stDob
           ,stJoinDt
    FROM student stu
    WHERE
    DATEDIFF(yy,stu.stDob,stu.stJoinDt) >= 18 
    AND  DATEDIFF(yy,stu.stDob,stu.stJoinDt) < 75

是否还有其他有效的方法可以编写datediff来捕获所有丢失的记录?

The missing records are
stDob             stJoinDt
10/08/1925        2011-01-03
04/18/1935        2011-01-19
12/11/1928        2011-06-06
1/24/1927         2011-04-18
04/18/1918        2011-04-20

1 个答案:

答案 0 :(得分:2)

这些记录应该缺失,因为stDob和stJoinDt之间的年数不是介于18和75之间,因为你要根据stDob和stJoinDt相差18到75年:

with student as (
    select 'Bob' as stName, 1 as stId, '10/08/1925' as stDob,        '2011-01-03' as stJoinDt
    union select 'Bob' as stName, 2 as stId, '04/18/1935',        '2011-01-19'
    union select 'Bob' as stName, 3 as stId, '12/11/1928',        '2011-06-06'
    union select 'Bob' as stName, 4 as stId, '1/24/1927 ',        '2011-04-18'
    union select 'Bob' as stName, 5 as stId, '04/18/1918',        '2011-04-20'
)
    SELECT stName
           ,stId
           ,stDob  --(varchar(15))
           ,stJoinDt --(datetime)
           ,datediff(yy, stu.stDob, stu.stJoinDt) as DiffYears
    FROM student stu

输出:

stName  stId    stDob           stJoinDt    DiffYears
Bob     1       10/08/1925      2011-01-03  *86* (>75)
Bob     2       04/18/1935      2011-01-19  *76* (>75)
Bob     3       12/11/1928      2011-06-06  *83* (>75)
Bob     4       1/24/1927       2011-04-18  *84* (>75)
Bob     5       04/18/1918      2011-04-20  *93* (>75)

我的猜测是你想要捕获这个人至少18岁的所有记录。在这种情况下,从过滤器中删除75部分:

WHERE
DATEDIFF(yy,stu.stDob,stu.stJoinDt) >= 18 
-- STOP HERE

虽然从技术上讲这不会执行正确的计算,因为它只是找到年份值的差异而不考虑日期和月份。例如,即使该人只有17岁,1天,出生日期为12/31/1990,加入日期为1/1/2008,则登记为18年。我建议改为使用this question中提供的解决方案:

where
    (DATEDIFF(YY, stu.stDob, stu.stJoinDt) -
        CASE WHEN( 
            (MONTH(stDob)*100 + DAY(stDob)) > (MONTH(stJoinDt)*100 + DAY(stJoinDt))
        ) THEN 1 ELSE 0 END
    ) >= 18