根据oracle中的现有行数据填充其他行

时间:2018-06-25 17:15:10

标签: oracle pivot case

我有一个现有的表,其结构和示例数据如下:

+----------+-------+--------+--------+
| S.No     | Desc  | ACC ID | Value  |
+----------+-------+--------+--------+
| 1        | abc   | ACC_1  | 1.23   |  
+----------+-------+--------+--------+

根据业务条件

select S.No, desc,
case when acc id=ACC_1 then value else 0 end as ACC_2,
case when acc id=ACC_1 then value else 0 end as ACC_3,
case when acc id=ACC_1 then value else 0 end as ACC_4,
from table1

当前输出:

+----------+-------+--------+--------+--------+
| S.No     | Desc  | ACC_2  | ACC_3  | ACC_4  |     
+----------+-------+--------+--------+--------+
| 1        | abc   | 1.23   | 1.23   |1.23    |
+----------+-------+--------+--------+--------+

具有相同业务逻辑的必需输出:

+----------+-------+--------+--------+
| S.No     | Desc  | ACC ID | Value  |
+----------+-------+--------+--------+
| 1        | abc   | ACC_2  | 1.23   |
+----------+-------+--------+--------+
| 1        | abc   | ACC_3  | 1.23   |
+----------+-------+--------+--------+
| 1        | abc   | ACC_4  | 1.23   |
+----------+-------+--------+--------+

1 个答案:

答案 0 :(得分:1)

使用具有TABLE1结构的CROSS联接SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 3,如下所示:

select t."S.No", t."Desc", rtrim(t."ACC ID",1)||level "ACC ID", t."Value"
  from dual d
  cross join table1 t
 connect by level <= 3; 

SQL Fiddle Demo