SQL查询将具有唯一值的列转换为行

时间:2019-12-09 15:20:23

标签: sql pivot

我对SQL编程非常陌生,因此很难满足以下要求

BARCODE    MATERIAL  SET WEIGHT
112345     PBR1          34
112345     PBR2          34
112346     PBR11          34
112346     PBR21          34
112347     PBR43         34

所需的输出

BARCODE    MATERIAL  SET WEIGHT     MATERIAL  SET WEIGHT
112345     PBR1          34           PBR2          34
112346     PBR11          34          PBR21          34
112347     PBR43          34     

请帮助

1 个答案:

答案 0 :(得分:0)

您可以使用row_number()和条件聚合:

select
    barcode,
    material,
    max(case when rn = 1 then set_weight end) set_weight1,
    max(case when rn = 1 then material   end) material1,
    max(case when rn = 2 then set_weight end) set_weight2,
    max(case when rn = 2 then material   end) material2
from (
    select
        t.*,
        row_number() over(partition by barcode order by material) rn
    from mytable t
) t