将金额为 x 的记录复制到金额 = 1 的另一个 table 中的 x 个实例

copy a record with amount x to x instances in another table with amount = 1

我的 SQL 技能足以满足我的大部分需求,但这超出了我的知识范围。我试图在 Object Pascal 中编写一个生成 SQL 的程序,但它很慢。

我有一个 table 包含金额 = 或 > 1 的记录。 现在我想将这些记录复制到另一个 table "amount" 次,这样 数量为1的记录被复制一次,数量为1 并且一条数量为5的记录被复制了5次,每次新的数量为1。

是否可以在 SQL 中执行此操作?

假设有两个表 sourcetarget:

create table source (
  id integer generated by default as identity constraint pk_source primary key,
  item_type integer not null,
  amount integer not null
);

create table target (
  id integer generated by default as identity constraint pk_target primary key,
  item_type integer not null,
  amount integer not null
);

其中 source 填充为:

insert into source (item_type, amount) values (1, 5);
insert into source (item_type, amount) values (2, 1);
insert into source (item_type, amount) values (3, 2);

然后您可以使用匿名程序 (execute block) 将这些记录复制到 target

execute block
as
declare item_type type of column source.item_type;
declare amount type of column source.amount;
begin
  for select item_type, amount from source into item_type, amount do
  begin
      while (amount > 0) do
      begin
        insert into target (item_type, amount) values (:item_type, 1);
        amount = amount - 1;
      end
  end
end

这会将记录从 source 复制到 target (amount) 次。

另请参阅此 dbfiddle