对不起,如果这是一个重复的问题,但我不知道要使用哪些搜索关键字(这也是问题模糊的原因)
我有一张这样的表
Parent_ID Parent_item Child_Item
1 A B
1 A C
2 H I
2 H J
2 H K
我希望得到以下格式的结果:
Parent_ID Parent_or_Child
1 A
1 B
1 C
2 H
2 I
2 J
2 K
如何做到这一点?
谢谢!
答案 0 :(得分:1)
您需要取消数据,使用UNION
select Parent_ID,Parent_item
from yourtable
Union
select Parent_ID,Child_Item
from yourtable
答案 1 :(得分:1)
您需要对数据进行取消操作,而您似乎不需要重复数据,因此您需要select distinct
。在Oracle 11.1或更高版本中,您可以使用UNPIVOT
运算符 - 优点是基表只能读取一次。
如果需要,可以添加order by
子句;我没有,所以输出中的行是按任意顺序排列的(如果你比较你的"所需的输出")。
with
test_data ( Parent_ID, Parent_item, Child_Item ) as (
select 1, 'A', 'B' from dual union all
select 1, 'A', 'C' from dual union all
select 2, 'H', 'I' from dual union all
select 2, 'H', 'J' from dual union all
select 2, 'H', 'K' from dual
)
-- End of test data (NOT part of the query).
-- SQL query begins BELOW THIS LINE.
select distinct parent_id, parent_or_child
from test_data
unpivot (parent_or_child
for col in (parent_item as 'parent_item', child_item as 'child_item'))
;
PARENT_ID PARENT_OR_CHILD
---------- ---------------
2 I
1 A
1 B
1 C
2 H
2 J
2 K
7 rows selected.