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

时间:2019-03-07 15:38:47

标签: sql database oracle

我有一个表,其中包含一些ID,这些ID与我想摆脱的重复数据相对应。它们通过组号链接。目前,我的数据如下:

|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|

谢谢您的时间。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;

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

相关问题