convert rows into column in db2

纵饮孤独 提交于 2019-12-08 15:22:16

问题


I need the below select results to be converted into single row ,

Actual output:

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

Expected Output:

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

How to achieve the expected output in db2?


回答1:


Following SQL will do the job:

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



回答2:


Try something like this:

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


来源:https://stackoverflow.com/questions/44784095/convert-rows-into-column-in-db2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!