How to pivot row data into specific columns db2

空扰寡人 提交于 2021-01-07 06:24:01

问题


I would like to pivot results from a table into a new structure. So that it can map all the children to the parent product.

Current Result

Parent_Prod_Num|Child_Prod_Num|Child_Prod_Code|Child_Prod_Name
1|11|a123|a
1|12|b123|ab
1|13|c123|abc

Expected Result

Parent_Prod_Num|Child_Prod_Num_1| Child_Prod_Code_1|Child_Prod_Name_1| Child_Prod_Num_2| Child_Prod_Code_2|Child_Prod_Name_2| Child_Prod_Num_3| Child_Prod_Code_3|Child_Prod_Name_3
1|11|a123|a|12|b123|ab|13|c123|abc

回答1:


For a fixed maximum number of children per parent, you can enumerate the rows with row_number(), then pivot with conditional aggregation:

select parent_prod_num,
    max(case when rn = 1 then child_prod_num  end) as child_prod_num_1,
    max(case when rn = 1 then child_prod_code end) as child_prod_code_1,
    max(case when rn = 1 then child_prod_name end) as child_prod_name_1,
    max(case when rn = 2 then child_prod_num  end) as child_prod_num_2,
    max(case when rn = 2 then child_prod_code end) as child_prod_code_2,
    max(case when rn = 2 then child_prod_name end) as child_prod_name_2,
    max(case when rn = 3 then child_prod_num  end) as child_prod_num_3,
    max(case when rn = 3 then child_prod_code end) as child_prod_code_3,
    max(case when rn = 3 then child_prod_name end) as child_prod_name_3
from (
    select t.*, row_number() over(partition by parent_prod_num order by child_prod_num) rn
    from mytable t
) t
group by parent_prod_num


来源:https://stackoverflow.com/questions/63959390/how-to-pivot-row-data-into-specific-columns-db2

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