2017-04-12 87 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