简体   繁体   English

如何在oracle sql中提取两个日期之间的天数?

[英]How to extract No. of Days between 2 dates in oracle sql?

I want No. of days between these 2 dates using Oracle SQL 我想使用Oracle SQL在这两个日期之间的天数

Dates: 日期:

BETWEEN "1/1/2018" AND "6/11/2018"

How to write SQL Query? 如何编写SQL查询?

between date '2018-01-01' and date '2018-11-06'

where DATE literal looks exactly like that: DATE 'YYYY-MM-DD' DATE文字看起来完全像这样: DATE 'YYYY-MM-DD'

In your example: 在您的示例中:

  • double quote's can't be used 不能使用双引号
  • even if you used single quotes, that would be a string, not DATE so you'd depend on whether Oracle is capable of converting it (implicitly) to date or not 即使您使用单引号,也可能是字符串,而不是DATE,因此您将取决于Oracle是否能够(隐式)将其转换为日期
  • therefore, always use dates, not strings 因此,请始终使用日期,而不是字符串

[EDIT] [编辑]

This is how you select the whole calendar between those two dates: 这是您在这两个日期之间选择整个日历的方式

select date '2018-01-01' + level - 1
from dual
connect by level <= date '2018-11-06' - date '2018-01-01' + 1;

As other answers have pointed out you can simply divide two dates, but there is also no need for any additional arithmetic. 正如其他答案所指出的那样,您可以简单地将两个日期相除,但是也不需要任何其他算术。

The code: 编码:

select to_date('6/11/2018', 'DD/MM/YYYY') - to_date('1/1/2018', 'DD/MM/YYYY')
  from dual;

The result: 309 结果:309

Just use 只需使用

select date'2018-11-06' - date'2018-01-01' + 1 as days_difference
  from dual;

DAYS_DIFFERENCE
---------------
     310

or 要么

with t( myDate ) as
(
 select date'2018-11-06' from dual union all 
 select date'2018-01-01' from dual
)
select max(myDate) - min(myDate) + 1 as days_difference
  from t;

DAYS_DIFFERENCE
---------------
     310

you can simple do: 您可以简单地执行以下操作:

select date1-date2 form dual;

or 要么

select (sysdate-to_date('01-jan-2018'))-(sysdate-to_date('10-jan-2018'))from dual;

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

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