Home > Software engineering >  SQL Code to Determine IF Test Date of (A) is Within N Days of Test Date (B) then Return Members Row
SQL Code to Determine IF Test Date of (A) is Within N Days of Test Date (B) then Return Members Row

Time:01-10

I'm writing a SQL query in Teradata to determine which members had an eGFR and uACR test done within 4 days of each other. All of the tests are being pulled in correctly, but not sure who to go about this in the WHERE clause. SQL Code Sample

I only need data returned where this is true.

I tried this

AND [uACR_2b_2_DATE] <= ([uACR_2b_1_DATE]   4 Days)

also other attempt

sample code2

CodePudding user response:

In sql server there is DATEDIFF to determine the distance, this works with days, hours, etc.

DECLARE
 @dt1 DATETIME = '20230102 23:59:59' 
 ,@dt2 DATETIME = '20230103 00:00:00'


SELECT difference_ABS = ABS( DATEDIFF(DAY, @dt1, @dt2) )

This ignores the time part, and gives the absolute (no negatives) of the distance of the date part. So in this example You get one day distance, although the two timestamps are one minute apart. If this is what You would like to use, just put it in a WHERE-CLAUSE like so

ABS( DATEDIFF(DAY, uACR_2b_1_DATE, uACR_2b_2_DATE) ) <= 4
  • Related