Oracle SQL:从Join中的Date返回的Weeks

问题描述 投票:1回答:2

我有一张表有几年的交易表,其中也包含了一年中的一周数字列(1-53)。我想加入该表并回顾每年/每周的组合,这些行是从一年/一周开始的12周。例如,如果我有2018年第15周,我想总结2018年的5-14周。

由于多年,我不能只看周数之间的差异。

是否有允许此加入条件的函数或方法?

sql oracle
2个回答
1
投票

我想下面你的log表和connect by level <= 53连接在一起的机制可能会有所帮助:

  with log_mytable( transaction_time ) as
  (
   select timestamp'2019-04-08 14:53:23' from dual union all
   select timestamp'2018-04-04 08:25:16' from dual union all
   select timestamp'2018-04-03 12:11:05' from dual union all
   select timestamp'2018-03-03 18:05:06' from dual union all
   select timestamp'2018-03-03 17:15:46' from dual union all 
   select timestamp'2018-03-03 14:05:36' from dual union all 
   select timestamp'2018-02-06 23:05:42' from dual union all 
   select timestamp'2018-01-15 03:24:31' from dual union all 
   select timestamp'2018-01-01 00:15:27' from dual
  ), t as 
   (
   select to_char(transaction_time,'yyyyiw') as transaction_time, 
          substr('&i_week',-2)- lvl + 1 as flag, -- '&i_week' = 201814 whenever prompted
          max(to_char(transaction_time,'yyyyiw')) over (order by lvl desc) 
                                             as max_transaction_time
     from log_mytable   
     right join ( select level as lvl from dual connect by level <= 53 )
       on lvl = substr(to_char(transaction_time,'yyyyiw'),-2) 
      and to_char(transaction_time,'yyyyiw') <= '&i_week'      
   ) 
  select max_transaction_time - flag + 1 as "Week", 
         count(t.transaction_time) as "Count" 
    from t 
   where flag between 1 and 12
   group by max_transaction_time - flag + 1
   order by "Week" desc;

   Week     Count
   201814   2
   201813   0
   201812   0
   201811   0
   201810   0
   201809   3
   201808   0
   201807   0
   201806   1
   201805   0
   201804   0
   201803   1

1
投票

不确定你的列是如何定义的,但我已经解决了你的问题。

with data(year, week, value) as(
SELECT 2018  year
     , Level week
     , 1     value
FROM DUAL
CONNECT BY LEVEL <= 53
union all
SELECT 2017  year
     , Level week
     , 1     value
FROM DUAL
CONNECT BY LEVEL <= 53
) 
select 'Sum values 12 weeks before ' || :year ||' '||:week, sum(value) from data
where 1=1
and (year = :year 
and week < :week
and week >= :week -12)
or ( year =:year -1
and week >= case when :week -12 <=0 then (:week -12 + 53) end)
© www.soinside.com 2019 - 2024. All rights reserved.