简体   繁体   中英

Oracle SQL TOAD - Update Year in a variable ( Concat string + Year ) depending of Sysdate

I would like to Update Year in a variable ( string + Year ) depending of Sysdate

I want to execute a 'select' command more or less like that :

If sysdate is between 1st of October and 31 December

select * from table where table.date between CONCAT
('1/10/','Variable_Year_Current' )AND CONCAT
('30/09/','Variable_Year+1')

Else if sysdate is between 1 January and 30 of September

select * from table
where table.date 
between CONCAT ('1/10/','Variable_Year-1' )
AND CONCAT ('30/09/','Variable_Year_Current')

This query worked for test data:

with 
  a as (select 1970 var, to_char(sysdate, 'mm-dd') today from dual),
  b as (select case when today between '10-01' and '12-31' 
                    then to_date(var  ||'-10-01', 'yyyy-mm-dd')
                    else to_date(var-1||'-10-01', 'yyyy-mm-dd') end d1,
               case when today between '10-01' and '12-31' 
                    then to_date(var+1||'-09-30', 'yyyy-mm-dd')
                    else to_date(var  ||'-09-30', 'yyyy-mm-dd') end d2
           from a)
select test.* from b, test 
  where tdate between b.d1 and b.d2

SQLFiddle demo

In first line change 1970 to 'variable' year.


'2015 var' must not be defined bymyself. 'Year var' should be defined by sysdate.

It was not quite clear what you mean as variable. You can use extract(year from sysdate) for this:

with 
  a as (select extract(year from sysdate) var, 
               to_char(sysdate, 'mm-dd') today from dual),
  b as (select case when today between '10-01' and '12-31' 
                    then to_date(var  ||'-10-01', 'yyyy-mm-dd')
                    else to_date(var-1||'-10-01', 'yyyy-mm-dd') end d1,
               case when today between '10-01' and '12-31' 
                    then to_date(var+1||'-09-30', 'yyyy-mm-dd')
                    else to_date(var  ||'-09-30', 'yyyy-mm-dd') end d2
           from a)
select test.* from b, test 
  where tdate between b.d1 and b.d2

The WITH clause is so called subquery-factoring, I often use it to make steps more readable and when I need repeated references to the same data. Everything rest you have written you understood correctly except we do not "create" physical tables, this work like subqueries.

Subquery 'a' prepares data (year and today date as 'MM-DD') for further treatment, subquery b gets maximum and minimum period dates according to logic from question, last select just gathers data using these dates.

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