公司每年使用以下命名约定生成三批:YYYY11,YYYY22,YYYY33
在这种情况下batch_id =1
所有批次都是顺序的。但是,batches 200933
和201022
的缺席会导致batch_id=2
不顺序。
with batch_sequences as(
select 1 as batch_sequence, '200911' as batch_date from dual union all
select 2 as batch_sequence, '200922' as batch_date from dual union all
select 3 as batch_sequence, '200933' as batch_date from dual union all
select 4 as batch_sequence, '201011' as batch_date from dual union all
select 5 as batch_sequence, '201022' as batch_date from dual union all
select 6 as batch_sequence, '201033' as batch_date from dual),
batch_entries as
(
select 1 as batch_id, '200911' as batch_date from dual union all
select 1 as batch_id, '200922' as batch_date from dual union all
select 1 as batch_id, '200933' as batch_date from dual union all
select 1 as batch_id, '201011' as batch_date from dual union all
select 1 as batch_id, '201022' as batch_date from dual union all
select 1 as batch_id, '201033' as batch_date from dual union all
select 2 as batch_id, '200911' as batch_date from dual union all
select 2 as batch_id, '200922' as batch_date from dual union all
select 2 as batch_id, '201011' as batch_date from dual union all
select 2 as batch_id, '201033' as batch_date from dual
)
select batch_sequence,
e.batch_id,
s.batch_date,
lead(batch_sequence,1) over (order by batch_sequence) as next_batch
from batch_entries e
inner join batch_sequences s on e.batch_date=s.batch_date
order by e.batch_id,
e.batch_date;
我想我可以对铅值进行数学运算,但我没有得到所有的数据 batch_sequence值可以正确计算它。
问题
如何编写查询以显示batch_id=1
有'完美运行'且batch_id=2
错过了一些batch_dates?
我会满足于任何可以突出显示此结果的结果集。
答案 0 :(得分:1)
根据batch_id
为每个batch_date
分配一个序号,并将其与batch_sequence
进行比较:
with cte as
(
select batch_id, batch_date,
row_number() -- sequential number
over (partition by batch_id
order by batch_date) as rn
from batch_entries
)
select e.batch_id
from cte e join batch_sequences s
on e.batch_date=s.batch_date
group by e.batch_id
-- if there's no missing batch the difference will always be the same
having min(s.batch_sequence - e.rn) <> max(s.batch_sequence - e.rn)
请参阅fiddle
第二批数据:
batch_date rn batch_sequence batch_date
'200911' -> 1 1 '200911'
'200922' -> 2 2 '200922'
3 '200922'
'201011' -> 3 4 '201011'
5 '201022'
'201033' -> 4 6 '201033'