2017-04-12 88 views
0

我似乎无法获取将以下查询转换为枢轴SQL的逻辑。我的表有20列与他们的角色,我想将这些列转换成行,所以当导出到Excel时,我可以过滤一个列,因为值可以在20列相同。到目前为止,我所做的是转换20列到一个单一的一个,然后拆分单一到行:将SQL查询转换为枢纽

select  distinct TASKID, 
      regexp_substr(t.roles,'[^|]+', 1, lines.column_value) as role 
from  (
      select TASKID, 
         TRIM(ROLE1) || '|' || 
         TRIM(ROLE2) || '|' || 
         TRIM(ROLE3) || '|' || 
         TRIM(ROLE4) || '|' || 
         TRIM(ROLE5) || '|' || 
         TRIM(ROLE6) || '|' || 
         TRIM(ROLE7) || '|' || 
         TRIM(ROLE8) || '|' || 
         TRIM(ROLE9) || '|' || 
         TRIM(ROLE10) || '|' || 
         TRIM(ROLE11) || '|' || 
         TRIM(ROLE12) || '|' || 
         TRIM(ROLE13) || '|' || 
         TRIM(ROLE14) || '|' || 
         TRIM(ROLE15) || '|' || 
         TRIM(ROLE16) || '|' || 
         TRIM(ROLE17) || '|' || 
         TRIM(ROLE18) || '|' || 
         TRIM(ROLE19) || '|' || 
         TRIM(ROLE20) as roles 
      from  menu_roles 
      where  RLTYPE='58' 
     ) t, 
      TABLE(CAST(MULTISET(select LEVEL from dual connect by instr(t.roles, '|', 1, LEVEL - 1) > 0) as sys.odciNumberList)) lines 
where  regexp_substr(t.roles,'[^|]+', 1, lines.column_value) is not null 
order by regexp_substr(t.roles,'[^|]+', 1, lines.column_value) 

我会理解的,使用PIVOT会更有效率VS串联和分裂的字符串。

谢谢!

+0

有关使用'UNION',而不是如何? 'select taskid,role1 from menu_roles where rltype = '58'union select taskid,role2 from menu_roles where rltype = '58'union ...' –

+0

你的问题中没有PL/SQL –

+0

@a_horse_with_no_name:你是什么意思? – Jaquio

回答

1

你似乎想UNPIVOT

SELECT task_id, 
     role 
FROM menu_roles 
UNPIVOT (role FOR role_number IN (ROLE1, ROLE2, ROLE3, ROLE4 /*, ... */)); 

或者,使用UNION ALL

  SELECT task_id, role1 AS role FROM menu_roles 
UNION ALL SELECT task_id, role2 AS role FROM menu_roles 
UNION ALL SELECT task_id, role3 AS role FROM menu_roles 
UNION ALL SELECT task_id, role4 AS role FROM menu_roles 
-- ... 
+0

谢谢@ MT0。 UNPIVOT确实是我一直在寻找的 – Jaquio