如何根据DB2 for i上的生效日期确定取消日期?

tv6aics1  于 11个月前  发布在  DB2
关注(0)|答案(1)|浏览(130)

我尝试根据查找下一个有效日期并减去一天来确定前一行的到期日来设置取消日期。我有多个项目唯一关键的项目和有效日期(ACEFF),我想反向工程的“期望”(到期)日期,列ACCAN从“有效”日期。最新的项目将具有空的到期日期。
| 关键|有效|(期望)|
| --|--|--|
| A1| 2023年1月1日|2023年1月31日|
| A1| 2019 - 01 - 22 01:00:00| 2023年02月28日|
| A1| 2019 - 01 - 21 10:00:00||
| A2| 2023年1月1日|2019 - 01 - 15 00:00:00|
| A2| 2019 - 01 - 16 00:00:00| 2023年1月31日|
| A2| 2019 - 01 - 22 01:00:00||
这段代码(最初来自这个网站IIRC)应该,但并不一致(在某些情况下,它错误地传播一个exipitation日期跨越多行)。

UPDATE frp011i a
    SET a.accan = IFNULL((SELECT b.aceff - 1 DAY
                        FROM frp011i b
                        WHERE a.accust = b.accust
                          AND a.ackey  = b.ackey
                          AND a.actc   = b.actc
                          AND a.aceff  < b.aceff
                          AND a.accan  = '0001-01-01' FETCH FIRST ROW ONLY),'0001-01-01')
    WHERE a.accan = '0001-01-01' 
    ORDER BY a.accust,a.ackey,a.actc,a.aceff DESC WITH NC

语句逻辑:对于没有到期日期的每一行(“a”),在同一组(除了生效日期之外,键相同)中查找具有 * 更早 * 生效日期的行(“B”),然后使“a”行的到期日期比“B”的生效日期早一天。
在测试前重置导出的失效日期。不存在重复行。过期日期不是关键。该表没有重复副本。执行环境稳定,不起眼。执行和错误日志是干净的。不存在分配或记录锁定错误。
谢谢你的帮忙。
意想不到的结果,通常以一个无关的日期的形式出现,将其作为失效日期.脚本日志显示没有错误。

vdgimpew

vdgimpew1#

下面是一种使用mergelead(...) over(...)的方法(适用于DB2 for I 7.3)

create table table1 (key char(2), effective date, cancel date)
insert into table1 (key, effective)
  VALUES
  ('A1', date '2023-01-01'),
  ('A1', '2023-02-01'),
  ('A1', '2023-03-01'),
  ('A2', '2023-01-01'),
  ('A2', '2023-01-16'),
  ('A2', '2023-02-01')
select * from table1

| 关键|有效|取消|
| --|--|--|
| A1| 2023-01-01 2023-01-01| * 空 *|
| A1| 2023-02-01| * 空 *|
| A1| 2023-03-01 2023-03-01 2023-03-01| * 空 *|
| A2| 2023-01-01 2023-01-01| * 空 *|
| A2| 2023-01-16| * 空 *|
| A2| 2023-02-01| * 空 *|

select
  key,
  effective,
  lead(effective) over(partition by key order by effective) - 1 day as cancel
from table1

| 关键|有效|取消|
| --|--|--|
| A1| 2023-01-01 2023-01-01| 2023-01-31 - 2023-01-31|
| A1| 2023-02-01| 2023-02-28 2023-02-28 2023-02-28|
| A1| 2023-03-01 2023-03-01 2023-03-01| * 空 *|
| A2| 2023-01-01 2023-01-01| 2023-01-15 2023-01-15 2023-01-15|
| A2| 2023-01-16| 2023-01-31 - 2023-01-31|
| A2| 2023-02-01| * 空 *|

merge into table1 using (
  select
    key,
    effective,
    lead(effective) over(partition by key order by effective) - 1 day as cancel
  from table1
) as a on (table1.key, table1.effective) = (a.key, a.effective)
when matched then update set cancel = a.cancel
select * from table1

| 关键|有效|取消|
| --|--|--|
| A1| 2023-01-01 2023-01-01| 2023-01-31 - 2023-01-31|
| A1| 2023-02-01| 2023-02-28 2023-02-28 2023-02-28|
| A1| 2023-03-01 2023-03-01 2023-03-01| * 空 *|
| A2| 2023-01-01 2023-01-01| 2023-01-15 2023-01-15 2023-01-15|
| A2| 2023-01-16| 2023-01-31 - 2023-01-31|
| A2| 2023-02-01| * 空 *|
fiddle

相关问题