Sql将两列提取为两行

时间:2016-01-28 07:30:59

标签: sql oracle

我在Oracle表中有两个字段,并将它们添加到一个表中。

| Name       | brand       | Details      |
|:-----------|------------:|:------------:|
| Shirt      |        Ethos|   XXX  
| Mobile     |      Apple  |    XXX
| Laptop     |        Acer |    XXX 
| Mouse      |          HP |    XXX  
| Notepad    |       Archee|    XXX
| Coffee cup |     IKAI    |   XXX

从上表中我需要将Name和Brand作为行

添加到新表中

如下所示

Sno   |  Keywords
 1    |  Shirt
 2    |  Ethos
 3    |  Mobile
 4    |  Apple
 5    |  Laptop

有可能实现这个目标吗?

2 个答案:

答案 0 :(得分:1)

您可以使用UNION ALL和序列来生成Sno

CREATE SEQUENCE my_seq;

INSERT INTO new_table(Sno, Keywords)
SELECT my_seq.nextval, Name FROM old_table
UNION ALL
SELECT my_seq.nextval, Brand FROM old_table;

答案 1 :(得分:0)

您可以像这样生成sno

WITH ids ( rn, name, brand ) AS (
  SELECT ROWNUM, Name, Brand
  FROM   Your_Table
)
SELECT 2*RN - 1 AS sno,
       Name AS Keywords
FROM   ids
UNION ALL
SELECT 2*RN,
       Brand
FROM   ids;