SQL 甲骨文日期范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2038866/
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 05:01:25  来源:igfitidea点击:

oracle date range

sqloracledateplsqloracle10g

提问by Hoax

using a Oracle 10g db I have a table something like this:

使用 Oracle 10g db 我有一个像这样的表:

 create table x(
 ID NUMBER(10) primary key,
 wedding DATE NOT NULL
 );

how can I

我怎样才能

 select * from x where wedding is in june 2008???

I know it is probably an easy one but I couldn't find any satisfying answer so far. Help is very much appreciated.

我知道这可能很简单,但到目前为止我找不到任何令人满意的答案。非常感谢帮助。

回答by OMG Ponies

Use:

用:

SELECT *
  FROM x
 WHERE x.wedding BETWEEN TO_DATE('2008-JUN-01', 'YYYY-MON-DD') 
                            AND TO_DATE('2008-JUL-01', 'YYYY-MON-DD')

Use of TO_DATEconstructs a date with a time portion of 00:00:00, which requires the end date to be one day ahead unless you want to use logic to correct the current date to be one second before midnight. Untested:

Use ofTO_DATE构造一个时间部分为 00:00:00 的日期,这要求结束日期提前一天,除非您想使用逻辑将当前日期更正为午夜前一秒。未经测试:

TO_DATE('2008-JUN-30', 'YYYY-MON-DD') + 1 - (1/(24*60*60))

That should add one day to 30-Jun-2008, and then subtract one second in order to return a final date of 30-Jun-2008 23:59.

这应该将 30-Jun-2008 加一天,然后减去一秒以返回30-Jun-2008 23:59.

References:

参考:

回答by Roland Bouman

This is ANSI SQL, and supported by oracle as of version 9i

这是 ANSI SQL,从版本 9i 开始由 oracle 支持

SELECT *
FROM   x
WHERE  EXTRACT(YEAR  FROM wedding) = 2008
AND    EXTRACT(MONTH FROM wedding) =   06

Classic solution with oracle specific TO_CHAR():

oracle特定的经典解决方案TO_CHAR()

SELECT *
FROM   x
WHERE  TO_CHAR(wedding, 'YYYY-MMM') = '2008-JUN'

(the latter solutions was supported when dinosaurs still walked the earth)

(当恐龙还在地球上行走时,支持后一种解决方案)