如何将行数据转换为特定的列db2

时间:2020-09-18 16:20:58

标签: sql db2 pivot aggregate-functions window-functions

我想将表中的结果转换为新的结构。这样就可以将所有子项映射到父产品。

当前结果

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

预期结果

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 个答案:

答案 0 :(得分:1)

对于每个父母最大固定数目的孩子,您可以使用row_number()枚举行,然后使用条件聚合进行透视:

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