简体   繁体   中英

Compare date and time in SQL for DB2

I need to compare date and time of 2 fields and see if its greater than 24 hours however there is another field whose value is less than the 24 hours of the compared date. For example ,

  • create date - 18/7/2019 11:15 AM
  • target date - 19/07/2019 11:16 AM

There is a gap of 24 hours here

  • Actual date - 19/07/2019 10:45 AM

Actual date is less than above said gap of 24 hours . Hence the query should return such records that has actual date less than the create date and target date gap of 24 hours. Here all the fields are of DATETIME data type in DB2 database.

It's not clear what you really try to do.
Actual date is less than above said gap of 24 hours
How can a date may be comparable to a gap (or time duration)?
Should we understand it as:
Gap between actual and created is less than gap between target and created ?
If so, then try the following:

select *
from 
(
select create, target, actual
, timestampdiff(8, char(target - create)) gap_target
, timestampdiff(8, char(actual - create)) gap_actual
from table(values 
  (timestamp('2019-07-18-11.15.00'), timestamp('2019-07-19-11.16.00'), timestamp('2019-07-19-10.45.00'))
) t (create, target, actual)
) 
where 
gap_target >= 24 and gap_actual < 24
-- or some another expression like:
-- gap_actual < gap_target
;  

CREATE              TARGET              ACTUAL              GAP_TARGET GAP_ACTUAL
------------------- ------------------- ------------------- ---------- ----------
2019-07-18 11:15:00 2019-07-19 11:16:00 2019-07-19 10:45:00         24         23

Is this what you want?
If not, then provide a few number of input records and the exact result desired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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