Oracle Pivot 行到列模式匹配
Oracle Pivot rows to columns pattern matching
我想将行重新排列成列(在下面的 tbl2 中)以计算 EXEN col 的 EXEN 出现次数,以及 MPACODE 列以 MPA 开头的任何代码的出现次数。
SELECT *
FROM (select code from tbl2 where pidm='4062161')
PIVOT (count(*) FOR (code) IN ('EXEN' AS EXEN, 'MPA%' AS MPACODE));
tbl2:
期望的输出:
实际输出:
您必须执行一个中间步骤将所有 MPA%
转换为 MPA
请参阅子查询 dt2
with dt as (
select 'EXEN' code from dual union all
select 'MPA'||rownum from dual connect by level <= 10),
dt2 as (
select
case when code like 'MPA%' then 'MPA' else code end as code
from dt)
select *
from dt2
pivot (
count(*) for
(code) IN ('EXEN' AS EXEN, 'MPA' AS MPACODE));
EXEN MPACODE
---------- ----------
1 10
PIVOT
执行 相等 比较(不是 LIKE
),因此这是无效的:'MPA%' AS MPACODE
和 原因查询失败的原因。
例如:
select
count(case when code='EXEN' then 1 end) exen,
count(case when code like 'MPA%' then 1 end) mpacode
from tbl2 where pidm='4062161';