将SQL查询转换为pivot

时间:2017-04-12 11:18:41

标签: sql oracle

我似乎无法获得将以下查询转换为数据透视SQL的逻辑。我的表有20列,其中包含角色,我想将这些列转换为行,因此,当导出到Excel时,我可以对单个列进行过滤,因为20列上的值可以相同。到目前为止,我所做的是将20列转换为单个列,然后将该列拆分为行:

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会比连接和分割字符串更有效。

谢谢!

1 个答案:

答案 0 :(得分: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
-- ...