db2 - How to match starting date to the closest ending date in order to get the time difference -


select    out.emp_id,    out.dt_tm "datetimeout",     in.dt_tm "datetimein",    cast(timestampdiff( 4, char(timestamp(in.dt_tm) - timestamp(out.dt_tm))) decimal(30,1))/60 "duration out"  (    select       e1.emp_id,        e1.dt_tm            hr.timeout e1                month(e1.dt_tm)=09        , year(e1.dt_tm)=2016        , e1.cd='out' ) out  left join (     select        e2.emp_id,        e2.dt_tm             hr.timeout e2                month(e2.dt_tm)=09        , year(e2.dt_tm)=2016        , e2.cd='in'   ) in    on out.emp_id=in.emp_id 

trying closest datetimein match datetimeout. repeats same datetimeout , datetimein multiple times.

i think normal because table dont have constraint unique on emp_id, dt_tm , cd. if want unique result try :

    period (     select  e1.emp_id,  e1.dt_tm  hr.timeout e1        month(e1.dt_tm)=09 , year(e1.dt_tm)=2016     )     select  distinct out.emp_id,  in.dt_tm  datetimein, out.dt_tm datetimeout,     timestampdiff(2 , cast(timestamp(in.dt_tm) - timestamp(ifnull(out.dt_tm, current date)) char(22)) ) durationsecond     period in left outer join period out      on out.emp_id=in.emp_id , out.cd='out' , in.cd='in'     order 1, 2, 3 

like can see, use timestampdiff '2' first parameter second (you divided 60), use ifnull because left outer join (out.dt_tm can null) , distinct unique result


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -