我希望将行重新排列为列(在下面的tbl2中),以计数EXEN的出现次数,以及MPACODE列以MPA开头的任何代码。
SELECT *
FROM (select code from tbl2 where pidm='4062161')
PIVOT (count(*) FOR (code) IN ('EXEN' AS EXEN, 'MPA%' AS MPACODE));tbl2:

期望产出:

实际产出:

发布于 2022-02-02 13:48:31
必须执行中间步骤才能将所有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 10PIVOT执行相同的比较(不是LIKE),因此这是无效的:'MPA%' AS MPACODE和查询失败的原因。
发布于 2022-02-02 14:16:45
例如:
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';https://stackoverflow.com/questions/70956357
复制相似问题