如何从Oracle中的日期中提取年份?

时间:2018-11-30 03:05:04

标签: oracle

我不明白为什么以下查询不起作用

<input name="books[0].Title" type="text" value="sometitle">
<input name="books[0].Author" type="text" value="somevalue">

<input name="books[1].Title" type="text" value="sometitle">
<input name="books[1].Author" type="text" value="somevalue">

<!-- other input elements depending on books list count -->

它返回SELECT stringdate, TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate, EXTRACT(YEAR FROM MYDATE) as myyear FROM data.repo data WHERE ROWNUM <10"

但是,只需运行

ORA-00904: "MYDATE": invalid identifier

正确给予:

SELECT stringdate, TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate

这使我发疯。有什么问题谢谢!

2 个答案:

答案 0 :(得分:2)

问题是您不能在同一选择子句中引用别名“ mydate”。

SELECT
  stringdate
, EXTRACT(YEAR FROM MYDATE) as myyear
FROM (
    SELECT stringdate
    , TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate
    FROM data.repo data 
    WHERE ROWNUM <10
    )

还有其他可能性,例如

SELECT stringdate
    , TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate
    , to_number(substr(stringdate,1,4)) AS YR
FROM data.repo data 
WHERE ROWNUM <10

在Oracle中使用“ select *”(nb:在生产代码中不建议使用),您需要o使用表/子查询别名,例如:

SELECT
  d.*
, EXTRACT(YEAR FROM MYDATE) as myyear
FROM (
    SELECT data.*
    , TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate
    FROM data.repo data 
    WHERE ROWNUM <10
    ) d

答案 1 :(得分:1)

Select mydate, EXTRACT(YEAR FROM MYDATE) as myyear
From (
    SELECT stringdate, TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate
          /* , EXTRACT(YEAR FROM MYDATE) as myyear */
    FROM data.repo data 
    WHERE ROWNUM <10"
 ) A