简体   繁体   中英

Date and Time Difference in Oracle SQL

In Oracle SQL I have merged 4 columns (ex of column names: a_d , a_t , d_d , d_t ) into 2 columns (ex of names: a_d_t and d_d_t ) that are each of the format: YYYY-MMM-DD HH24:MI . I am trying to find how much time passed (days and hours), for each observation, between a_d_t (the starting time) and d_d_t (the ending time).

I have tried d_d_t - a_d_t and to_date(d_d_t)-to_date(a_d_t) , but I got back the following for each: invalid identifier .


For reference the code that I used (which worked), to merge the columns is:

to_char(to_date
( to_char (a_d,'YYYYMMDD')
    || a_t,
 'YYYYMMDDHH24MI'
   ), 'YYYY-MM-DD HH24:MI') 

Your inputs are strings, so you must convert them to dates. But it is not sufficient to say to_date, you must also give proper format models.

select to_date(d_d_t, 'yyyy-mm-dd hh24:mi') - to_date(a_d_t, 'yyyy-mm-dd hh24:mi') 
from   < ... >

will give you the difference in days. Multiply by 24, you will get it in hours.

Considering your inputs d_d_t, a_dare string in format yyyy-mm-dd hh:mi and nls_date_format is different from it, you can try to use following query and see, if it works.

To find the duration between two date, you have to convert your date string to the date format.

select col_a, col_b, to_date(col_a,'yyyy-mm-dd hh24:mi:ss')- to_date(col_b,'yyyy-mm-dd hh24:mi:ss')duration
from x_datedur

replace col_a with ending time, col_b with starting time and x_datedur with your tablename.

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