根据唯一ID将记录拆分为2个具有不同值的记录

问题描述 投票:1回答:2

我有一个表,其中包含一些ID,这些ID对应于我想要删除的重复数据。它们由groupid编号链接。目前我的数据如下所示:

|GroupID|NID1  |NID2  |
|S1     |644763|643257|
|T2     |4759  |84689 |
|W3     |96676 |585876|

为了运行软件,我需要以下格式的数据:

|GroupID|NID   |
|S1     |644763|
|S1     |643257|
|T2     |4759  |
|T2     |84689 |
|W3     |96676 |
|W3     |585876|

感谢您的时间。

sql database oracle
2个回答
3
投票

你想要union all

select groupid, nid1 as nid
from table t
union all -- use "union" instead if you don't want duplicate rows
select groupid, nid2
from table t;

0
投票

在Oracle 12C +中,您可以使用横向连接:

select t.groupid, v.nid
from t cross apply
     (select t.nid1 as nid from dual union all
      select t.nid2 as nid from dual
     ) v;

这比union all更有效,因为它只扫描一次表。

你也可以表达为:

select t.groupid,
       (case when n.n = 1 then t.nid1 when n.n = 2 then t.nid2 end) as nid
from t cross join
     (select 1 as n from dual union all select 2 from dual) n;

稍微复杂一点,但仍然只有一次扫描表。

© www.soinside.com 2019 - 2024. All rights reserved.