DB2/SQL: 如何在向 table 中插入数据时增加最大值

DB2/SQL: How to increment the max value when inserting data into table

我有 2 tables(tables:访问和购物篮)我需要一种方法将数据插入 table 购物篮,其中一些数据来自 table购物。

table: 访问

vis_ID vis_name vis_date
1 Mike 2021-12-09
2 Lu 2021-09-02
3 Luke 2021-03-04
4 James 2021-01-19

bas_ID 与 vis_ID 的 ID 相同。我想为所有访问 >= '2021-05-01' 的项目 'freebie' 插入购物篮,访问日期 'vis_date' 与字段购物篮日期 'bas_date'

相同

我的问题是,如果篮子里有物品,下一个篮子位置'bas_pos'应该是最大值+1。但是如果table篮子里没有篮子物品,bas_pos 应该是 1.

输出 table: 篮子

bas_ID bas_item bas_date bas_pos
1 cap 2021-12-09 1
1 ball 2021-12-09 2
1 fruit 2021-12-09 3
1 freebie 2021-12-09 4
2 freebie 2021-09-02 1

我想我必须用子选择来实现?我的代码适合 DB2 吗? 谢谢。

Insert into basket
  select vis_ID, 'freebie', vis_date, case when(select max(bas_pos) from basket b
                                       where b.bas_ID = c.vis_ID) is null then '1' else int(select vis_ID, 'freebie', vis_date, case when(select max(bas_pos) from basket b
                                       where b.bas_ID = c.vis_ID) +1 end
  from visit c
  where vis_date >= '2021-05-01'

试试这个:

Insert into basket (bas_ID, bas_item, bas_date, pas_pos)
select 
  c.vis_ID, 'freebie', c.vis_date
, coalesce (b.bas_pos, 0) + rn_
from
(
  select 
    vis_ID, vis_date
  , row_number () over (partition by vis_id) as rn_
  from visit
  where vis_date >= '2021-05-01'
) c
left join 
(
  select bas_ID, max (pas_pos) as bas_pos
  from basket 
  group by bas_ID
) b on b.bas_ID = c.vis_ID