SQL Oracle 中的 DATEDIFF 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28406397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:15:54  来源:igfitidea点击:

DATEDIFF function in Oracle

sqloracleselectdatediff

提问by user3601310

I need to use Oracle but DATEDIFF function doesn't work in Oracle DB.

我需要使用 Oracle 但 DATEDIFF 函数在 Oracle DB 中不起作用。

How to write the following code in Oracle? I saw some examples using INTERVAL or TRUNC.

下面的代码在oracle中怎么写?我看到了一些使用 INTERVAL 或 TRUNC 的示例。

SELECT DATEDIFF ('2000-01-01','2000-01-02') AS DateDiff;

回答by Mureinik

In Oracle, you can simply subtract two dates and get the difference in days. Also note that unlike SQL Server or MySQL, in Oracle you cannot perform a selectstatement without a fromclause. One way around this is to use the builtin dummy table, dual:

在 Oracle 中,您可以简单地减去两个日期并得到天数的差值。另请注意,与 SQL Server 或 MySQL 不同,在 Oracle 中,您不能执行select没有from子句的语句。解决此问题的一种方法是使用内置虚拟表dual

SELECT TO_DATE('2000-01-02', 'YYYY-MM-DD') -  
       TO_DATE('2000-01-01', 'YYYY-MM-DD') AS DateDiff
FROM   dual

回答by a_horse_with_no_name

Just subtract the two dates:

只需减去两个日期:

select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;

The result will be the difference in days.

结果将是天数的差异。

More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

手册中有更多详细信息:https:
//docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

回答by Patrick Hofman

You can simply subtract two dates. You have to cast it first, using to_date:

您可以简单地减去两个日期。您必须首先使用to_date

select to_date('2000-01-01', 'yyyy-MM-dd')
       - to_date('2000-01-02', 'yyyy-MM-dd')
       datediff
from   dual
;

The result is in days, to the difference of these two dates is -1(you could swap the two dates if you like). If you like to have it in hours, just multiply the result with 24.

结果以天为单位,这两个日期的差为-1(如果您愿意,可以交换两个日期)。如果您喜欢以小时为单位,只需将结果乘以 24。

回答by pavani chinthalapalli

We can directly subtract dates to get difference in Days.

我们可以直接减去日期以获得天数的差异。

    SET SERVEROUTPUT ON ;
    DECLARE
        V_VAR NUMBER;
    BEGIN
         V_VAR:=TO_DATE('2000-01-02', 'YYYY-MM-DD') - TO_DATE('2000-01-01', 'YYYY-MM-DD') ;
         DBMS_OUTPUT.PUT_LINE(V_VAR);
    END;