【问题标题】:Concatenate year to a date in Oracle SQL在 Oracle SQL 中将年份连接到日期
【发布时间】:2016-01-26 18:14:24
【问题描述】:

我正在尝试进行动态查询,以查找一年中两天(去年 7 月 1 日和今年 6 月 30 日)之间的所有日期。下面是我一直在尝试的查询的 where 子句:

and pbh.batch_date between
        ('30-JUN-'||extract(year from trunc(sysdate))-1))
    and ('01-JUL-'||extract(year from trunc(sysdate))))

这会返回不一致的数据类型错误:预期 DATE 得到 NUMBER。然后我尝试将它们转换为这样的日期:

and pbh.batch_date between
        to_date(( '01-JUL-'||extract(year from trunc(sysdate))-1))
    and to_date(( '30-JUN-'||extract(year from trunc(sysdate))))

但这现在返回一个无效数字错误。我不知道 pbh.batch_date 存储的格式是否有所不同,但它是 (m)m/(d)d/yyyy

【问题讨论】:

  • to_date 需要一种格式来处理输入字符串,但@dnoeth 的答案仍然很实用

标签: sql oracle date


【解决方案1】:

无需转换为字符串并返回:

and ph.batch_date >= add_months(trunc(sysdate,'YEAR'), -6) 
and ph.batch_date <  add_months(trunc(sysdate,'YEAR'), 6)

【讨论】:

  • 我希望它特别是在 7 月 1 日到 6 月 30 日之间。无论哪种方式都不完全是六个月
  • @Aignor:抱歉,我忘记添加'YEAR',已修复。
猜你喜欢
  • 2021-07-09
  • 1970-01-01
  • 2020-05-02
  • 2020-07-10
  • 2012-03-07
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
相关资源
最近更新 更多