DateDiff Missing few records
I am using the datediff function
SELECT stName
,stId
,stDob --(va开发者_JS百科rchar(15))
,stJoinDt --(datetime)
FROM student stu
WHERE
DATEDIFF(yy,stu.stDob,stu.stJoinDt) between 18 and 75
Since the between operator is not effective I have also changed the code to
SELECT stName
,stId
,stDob
,stJoinDt
FROM student stu
WHERE
DATEDIFF(yy,stu.stDob,stu.stJoinDt) >= 18
AND DATEDIFF(yy,stu.stDob,stu.stJoinDt) < 75
Is there any other effective way to write datediff to capture all the missing records?
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
Those records should be missing because the number of years between stDob and stJoinDt is not between 18 and 75, as you are filtering them out with your condition that stDob and stJoinDt differ by between 18 and 75 years:
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
Output:
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)
My guess would be you were wanting to capture all records where the person is at least 18 years old. In that case, remove the 75 part from the filter:
WHERE
DATEDIFF(yy,stu.stDob,stu.stJoinDt) >= 18
-- STOP HERE
Although technically this does not perform the correct calculation, because it is only finding the difference in the year values and not taking into account day and month. For instance, a date-of-birth of 12/31/1990 and a join date of 1/1/2008 would register as 18 years even though the person is only 17 years, 1 day old. I would recommend instead using the solution provided in 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
精彩评论