简体   繁体   English

Oracle SQL中的日期和时间差异

[英]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 . 在Oracle SQL我已经合并4列(列名前: a_da_td_dd_t )分为2列(名前: a_d_td_d_t ),它们各自的格式: 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). 我正在尝试查找a_d_t (开始时间)和d_d_t (结束时间)之间的每次观察经过了多少时间(天和小时)。

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 . 我已经尝试过d_d_t - a_d_tto_date(d_d_t)-to_date(a_d_t) ,但是我为每个返回了以下内容: 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. 但是仅仅说to_date还不够,您还必须提供适当的格式模型。

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. 乘以24,您将在数小时内得到它。

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. 考虑到您输入的d_d_t,格式为yyyy-mm-dd hh:mi的a_dare字符串和nls_date_format有所不同,您可以尝试使用以下查询,看看是否可行。

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. col_a替换为结束时间,将col_b为开始时间,并将x_datedur为您的表名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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