ORACLE:将行的不同列分组,不包括零

时间:2017-04-13 14:22:20

标签: sql oracle oracle11g

我有一个表(见下面的示例表数据),其中对应一个标识符,我有多个记录。我的要求是将每列中的不同非零数据分组为逗号分隔值,然后对应于每个标识符,获取单个记录,将这些组合数据放在单独的列而不是行中。

enter image description here

Desired Output

1 个答案:

答案 0 :(得分:0)

这个解决方案应该可行,即使不是最漂亮的。首先使用union将值列折叠为单个列,然后使用listagg进行汇总。

with a as (
select identifier
      ,rcd_nbr
      ,cola1 as value
from table
UNION ALL
select identifier
      ,rcd_nbr
      ,cola2 as value
from table
UNION ALL
select identifier
      ,rcd_nbr
      ,cola3 as value
from table
UNION ALL
select identifier
      ,rcd_nbr
      ,colb1 as value
from table
UNION ALL
select identifier
      ,rcd_nbr
      ,colb2 as value
from table
UNION ALL
select identifier
      ,rcd_nbr
      ,colb3 as value
from table
UNION ALL
select identifier
      ,rcd_nbr
      ,colc1 as value
from table
UNION ALL
select identifier
      ,rcd_nbr
      ,colc2 as value
from table
UNION ALL
select identifier
      ,rcd_nbr
      ,colc3 as value
from table
)

,b as (
select identifier, rcd_nbr, case when value = 0 then null else value end as value
from a
)

,c as (
select identifier
      ,rcd_nbr
      ,LISTAGG(value, ',') WITHIN GROUP (ORDER BY value) OVER (rcd_nbr) AS concat
from b
)

,d as (
select identifier
      ,case when rcd_nbr = 1 then concat else null end as col1_summary
      ,case when rcd_nbr = 2 then concat else null end as col2_summary
      ,case when rcd_nbr = 3 then concat else null end as col3_summary
from c
)

select identifier
      ,max(col1_summary) as col1_summary
      ,max(col2_summary) as col2_summary
      ,max(col3_summary) as col3_summary
from d
group by identifier