【问题标题】:Split one row to many in same database table在同一个数据库表中将一行拆分为多行
【发布时间】:2021-01-20 11:42:13
【问题描述】:

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

假设我们有这张桌子:

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 脚本/存储过程。

【问题讨论】:

    标签: sql oracle oracle-sqldeveloper oracle-sql-data-modeler


    【解决方案1】:

    您可以使用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

    【讨论】:

      【解决方案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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-18
        相关资源
        最近更新 更多