我试图根据查找下一个有效日期并减去一天来确定前一行的到期日期来设置取消日期。我有多个按项目和有效日期 (ACEFF) 唯一键入的项目,并且我想对“所需”(到期)日期、“有效”日期的 ACCAN 列进行逆向工程。最新商品的有效期为空。
钥匙 | 有效 | (所需) |
---|---|---|
A1 | 2023年1月1日 | 2023/01/31 |
A1 | 2023年2月1日 | 2023年2月28日 |
A1 | 2023/03/01 | |
A2 | 2023年1月1日 | 2023年1月15日 |
A2 | 2023年1月16日 | 2023/01/31 |
A2 | 2023年2月1日 |
此代码(最初来自此站点 IIRC)应该可以,但不能一致地工作(在某些情况下,它错误地将一个到期日期传播到多行)。
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”),在同一组中查找具有earlier有效日期的行(“b”)(除生效日期外键相同),然后使“a”行的到期日期比“b”的生效日期早一天。
在测试之前重置派生的到期日期。没有重复的行。到期日期不是关键。该表没有重复的副本。执行环境稳定,无异常情况。执行和错误日志都很干净。没有分配或记录锁定错误。
感谢您的帮助。
意外的结果,通常以不相关的日期作为到期日期的形式。脚本日志没有显示错误。
这是使用
merge
和 lead(...) over(...)
的一种方法
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 | 空 |
A1 | 2023-02-01 | 空 |
A1 | 2023-03-01 | 空 |
A2 | 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-31 |
A1 | 2023-02-01 | 2023-02-28 |
A1 | 2023-03-01 | 空 |
A2 | 2023-01-01 | 2023-01-15 |
A2 | 2023-01-16 | 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-31 |
A1 | 2023-02-01 | 2023-02-28 |
A1 | 2023-03-01 | 空 |
A2 | 2023-01-01 | 2023-01-15 |
A2 | 2023-01-16 | 2023-01-31 |
A2 | 2023-02-01 | 空 |