Я полагаю, что такой механизм ниже, где ваша таблица 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