Sql 如何将行数据透视到db2的特定列中

Sql 如何将行数据透视到db2的特定列中,sql,db2,pivot,aggregate-functions,window-functions,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_Pro

我想将结果从一个表透视到一个新的结构中。这样它就可以将所有子产品映射到父产品

当前结果

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

对于每个父级的固定最大子级数,可以使用
row\u 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

是否最多有三个子项?是的,父num最多可以有三个子项。只有一个小注释:您可以使用DECODE来简化语法,而不是CASE。g、 :MAX(解码(rn,1,child_prod_num))为child_prod_num1@PavolAdam:的确如此。我更喜欢
case
,因为它是标准的SQL,而且(几乎)所有数据库都支持它。