在同一数据库中将一行拆分为多行 table
Split one row to many in same database table
我们有一个要求,我们希望根据某些条件将一行拆分为多行(在同一个 table 中)。
假设我们有这个 table :
ID
Value
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
Value
1
V1
4
V1
5
V1
2
V2
3
V3
6
V3
我正在寻找一些 SQL script/Stored Proc 来帮助我实现同样的目标。
您可以使用 join
和派生的 table 生成行。 . .然后使用 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
。
您可以使用以下号码加入您的 table:
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)
我们有一个要求,我们希望根据某些条件将一行拆分为多行(在同一个 table 中)。
假设我们有这个 table :
ID | Value |
---|---|
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 | Value |
---|---|
1 | V1 |
4 | V1 |
5 | V1 |
2 | V2 |
3 | V3 |
6 | V3 |
我正在寻找一些 SQL script/Stored Proc 来帮助我实现同样的目标。
您可以使用 join
和派生的 table 生成行。 . .然后使用 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
。
您可以使用以下号码加入您的 table:
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)