如何在 Oracle 上使用 SQL 获取当前年份?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1119710/
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
How do I get the current year using SQL on Oracle?
提问by Craig Angus
I need to add the current year as a variable in an SQL statement, how can I retrieve the current year using SQL?
我需要在 SQL 语句中添加当前年份作为变量,如何使用 SQL 检索当前年份?
i.e.
IE
BETWEEN TO_DATE('01/01/**currentYear** 00:00:00', 'DD/MM/YYYY HH24:MI:SS') AND TO_DATE('31/12/**currentYear** 23:59:59', 'DD/MM/YYYY HH24:MI:SS')
回答by FerranB
Using to_char:
使用 to_char:
select to_char(sysdate, 'YYYY') from dual;
In your example you can use something like:
在您的示例中,您可以使用以下内容:
BETWEEN trunc(sysdate, 'YEAR')
AND add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60;
The comparison values are exactly what you request:
比较值正是您所要求的:
select trunc(sysdate, 'YEAR') begin_year
, add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60 last_second_year
from dual;
BEGIN_YEAR LAST_SECOND_YEAR
----------- ----------------
01/01/2009 31/12/2009
回答by borjab
Another option is:
另一种选择是:
SELECT *
FROM TABLE
WHERE EXTRACT( YEAR FROM date_field) = EXTRACT(YEAR FROM sysdate)
回答by Ali Elsayed Metwally
Use extract(datetime)
function it's so easy, simple.
使用extract(datetime)
功能就这么简单,简单。
It returns year, month, day, minute, second
它返回年、月、日、分、秒
Example:
例子:
select extract(year from sysdate) from dual;
回答by David Faber
Yet another option would be:
另一种选择是:
SELECT * FROM mytable
WHERE TRUNC(mydate, 'YEAR') = TRUNC(SYSDATE, 'YEAR');
回答by William Robertson
Since we are doing this one to death - you don't have to specify a year:
由于我们正在做这件事 - 您不必指定年份:
select * from demo
where somedate between to_date('01/01 00:00:00', 'DD/MM HH24:MI:SS')
and to_date('31/12 23:59:59', 'DD/MM HH24:MI:SS');
However the accepted answer by FerranB makes more sense if you want to specify all date values that fall within the current year.
但是,如果您想指定属于当前年份的所有日期值,FerranB 接受的答案更有意义。
回答by mohan
To display the current system date in oracle-sql
在 oracle-sql 中显示当前系统日期
select sysdate from dual;