我得到了一张包含4个字段的表格:
[record_id] is the pk
[pay_serial_number] should always be increased +1
[worker_id] each worker has unique id
[content] just some content.
我被告知添加功能有一个错误,并跳过许多序列号。 我需要创建一个查询,为每个工人打印缺少的序列号。
[worker_id][missing serial number]
[worker_id][missing serial number]
[worker_id][missing serial number]
打印此类表格的最快捷有效的方法是什么。
答案 0 :(得分:1)
查找“缺失”的序列号有点难。它们不在数据中,因此您必须生成它们。
然而,找到缺失的范围并不难。为此,使用相关子查询来获取下一个序列号(或使用lead()
或lag()
函数(如果可用)。然后找到任何有间隙的地方。
以下是查询:
select worker_id, pay_serial_number + 1 as FirstMissing,
(nextpsn - pay_serial_number - 1) as NumMissing
from (select t.*,
(select min(pay_serial_number)
from t_workers_pay t2
where t2.worker_id = t.worker_id and -- ASSUMING SEQUENTIAL FOR A WORKER
t2.pay_serial_number > t.pay_serial_number
) as nextpsn
from t_workers_pay t
) t
where nextpsn - pay_serial_number > 1;