简体   繁体   中英

Concatenate year to a date in Oracle SQL

I'm trying to make a query dynamic that looks for all the dates between two days of the year (July 1 of the last year and June 30th of this year). Below is the where clause of the query I've been attempting:

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

This returns an inconsistent datatypes error: expected DATE got NUMBER. I then tried casting them to dates like so:

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))))

But this now returns an invalid number error. I don't know if it makes a difference what format pbh.batch_date is stored as, but it's (m)m/(d)d/yyyy

There's no need to cast to a string and back:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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