将行转换为db2中的列

时间:2017-06-27 15:21:55

标签: db2 pivot

我需要将以下选择结果转换为单行

实际输出:

ORDER   POSTCODE    Quantity    Value
123456  AAAAA       22.78        5
123456  AAAAA       2.93         7

预期产出:

ORDER   POSTCODE    AmbientQuantity Ambientvalue FVQuantity FvVAlue
123456  AAAAA       22.78            5            2.93      7

如何在db2中实现预期的输出?

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

with tmp as (
    select f0.*, rownumber() over(partition by f0.ORDER, f0.POSTCODE) rang
    from your table f0
)

select 
f1.ORDER, f1.POSTCODE, f1.Quantity  AmbientQuantity, f1.Value Ambientvalue, 
f2.Quantity FVQuantity2, f2.Value FvVAlue2,
f3.Quantity FVQuantity3, f2.Value FvVAlue3,
f4.Quantity FVQuantity4, f2.Value FvVAlue4

from tmp f1 
left outer join tmp f2 on (f1.ORDER, f1.POSTCODE)=(f2.ORDER, f2.POSTCODE) and f2.rang=2
left outer join tmp f3 on (f1.ORDER, f1.POSTCODE)=(f3.ORDER, f3.POSTCODE) and f3.rang=3
left outer join tmp f4 on (f1.ORDER, f1.POSTCODE)=(f4.ORDER, f4.POSTCODE) and f4.rang=4
where f1.rang=1

答案 1 :(得分:0)

以下SQL将完成这项工作:

with temp as (
select ORDER, POSTCODE, QUANTITY, VALUE,
       rownumber() over (partition by ORDER, POSTCODE) as rownum
  FROM mytable2
 ) 
select ORDER, POSTCODE,
       max(case when rownum = 1 Then QUANTITY end) as AMBIENTQUANTITY, 
       max(case when rownum = 1 Then VALUE end) as AMBIENTVALUE, 
       max(case when rownum = 2 Then QUANTITY end) as FVQuantity, 
       max(case when rownum = 2 Then VALUE end) as FVVALUE
  from temp
 group by ORDER, POSTCODE