0

我们有一个要求,我们希望根据某些条件将一行拆分为多行(在同一个表中)。

假设我们有这张表:

ID 价值
1 V1
2 V2
3 V3

要求是,

  • 如果 ID=1,则将此行拆分为另外两行,其中新行的 ID 将为 4 和 5,并且值将仅为 V1(与 ID = 1 值相同)。
  • 如果 ID=2,不要拆分。
  • 如果 ID=3,则将此行拆分为另一行,其中新行的 ID 为 6,值仅为 V3(与 ID = 3 值相同)。

最终的 o/p 将是:

ID 价值
1 V1
4 V1
5 V1
2 V2
3 V3
6 V3

我正在寻找一些可以帮助我实现相同目标的 SQL 脚本/存储过程。

4

2 回答 2

3

join您可以使用派生表生成行。. . 然后用于union all引入现有行:

select id, value
from t
union all
select x.new_id, t.value
from t join
     (select 1 as old_id, 4 as new_id from dual union all
      select 1 as old_id, 5 as new_id from dual union all
      select 3 as old_id, 6 as new_id from dual 
     ) x
     on t.id = x.old_id;

如果您只想插入值,请insert与第二个查询一起使用。

于 2021-01-20T11:45:01.343 回答
2

您可以使用以下数字加入您的表格:

select case when t.id = 2 then t.id
            when t.id = 3 then t.id * lvl
            when t.id = 1 and lvl > 1 then lvl+2 
            else lvl 
      end as id, t.value 
  from your_table t
  cross join (select level as lvl from dual connect by level <=3)
where t.id = 1 or (t.id=2 and lvl=1) or (t.id = 3 and lvl <= 2)
于 2021-01-20T11:50:05.397 回答