Oracle SQL TOAD - 根据 Sysdate 更新变量中的年份(Concat 字符串 + 年份)

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

我想根据 Sysdate 更新变量(字符串 + 年份)中的年份

我想或多或少地执行一个 'select' 命令:

如果 sysdate10 月 1 日12 月 31 日之间

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

否则,如果 sysdate 介于 1 月 1 日9 月 30 之间

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

此查询适用于测试数据:

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

第一行将 1970 改为 'variable' 年。


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

不太清楚你所说的变量是什么意思。您可以为此使用 extract(year from sysdate)

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

WITH clause 就是所谓的子查询分解, 我经常使用它来使步骤更具可读性,以及当我需要重复引用相同数据时。 除了我们没有 "create" 物理表,你所写的一切你都理解正确, 这像子查询一样工作。

子查询'a'准备数据(年份和今天日期为'MM-DD')进行进一步处理, 子查询 b 根据问题的逻辑获取最大和最小周期日期, last select 只是使用这些日期收集数据。