SQL行值到列

时间:2018-04-19 20:22:33

标签: sql oracle pivot

我需要类似于PIVOT的帮助,但这并不容易。

我有这个结构的表,我需要获得类似于图片底部的结构:

PICTURE with exampe

任何人都可以帮助我吗? 谢谢你们!

2 个答案:

答案 0 :(得分:3)

以下是使用数据透视的解决方案:

with testdata as
(select 'first' casekey, 1 custom_field_id, 'value1' custom_field_value from dual union all
 select 'first' casekey, 2 custom_field_id, 'value2' custom_field_value from dual union all
 select 'first' casekey, 3 custom_field_id, 'value3' custom_field_value from dual union all
 select 'second' casekey, 6 custom_field_id, 'value1' custom_field_value from dual union all
 select 'second' casekey, 9 custom_field_id, 'value1' custom_field_value from dual)

select *
from(
select casekey, custom_field_id, custom_field_value,
       rank() over(partition by casekey order by custom_field_id) pivotRank
from testdata)
pivot(
    max(custom_field_id || ':' || custom_field_value)
    for pivotRank in (1 as CF1, 2 as CF2, 3 as CF3, 4 as CF4, 5 as CF5)
)

首先,我使用窗口函数对按casekey分区的custom_field_id列进行排名。然后你所要做的就是取你想要的连接字段的最大值,并在pivotRank上转1到5。

上述查询的输出如下所示:

casekey     CF1         CF2         CF3         CF4         CF5
first       1:value1    2:value2    3:value3    (null)      (null)
second      6:value1    9:value1    (null)      (null)      (null)

答案 1 :(得分:0)

试试这个:

with y as (
    select cas, cfi || ':' || cfv cf, ROW_NUMBER() over (partition by cas order by cfi) n
    from x)
  , z AS (
    select DISTINCT cas
    FROM x 
  )
select z.cas, cf1.cf, cf2.cf, cf3.cf, cf4.cf, cf5.cf
from z
left join y as cf1 on z.cas = cf1.cas and cf1.n = 1
left join y as cf2 on z.cas = cf2.cas and cf1.n = 2
left join y as cf3 on z.cas = cf3.cas and cf1.n = 3
left join y as cf4 on z.cas = cf4.cas and cf1.n = 4
left join y as cf5 on z.cas = cf5.cas and cf1.n = 5