行到PostgreSQL中的列

时间:2017-05-10 17:01:59

标签: postgresql pivot transpose

我有以下主表:

order_id    unique_order_id   article_price
    1             1A                100
    1             1B                200 
    1             1C                300
    2             2A                100

我希望得到以下结果:

order_id   article_priceA    article_priceB   article_priceC
    1            100                200              300
    2            100                null             null

我已经找到了一个解决方案,通过对每个unique_order进行主表的自连接(我将每个order_id(A,B,C,D)最多有4个不同的唯一订单,但是我想知道是否有这是一个更好的方法吗?

我目前的解决方案是这样的:

select 
a.order_id, 
a.article_price as article_priceA,
b.article_price as article_priceB, 
c.article_price as article_priceC

from main a 
left join main b on b.order_id=a.order_id and right(unique_order_id,1)='B' 
left join main c on b.order_id=a.order_id and right(unique_order_id,1)='C

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合:

select order_id,
    max(case when right(unique_order_id, 1) = 'A' then article_price end) as article_priceA,
    max(case when right(unique_order_id, 1) = 'B' then article_price end) as article_priceB,
    max(case when right(unique_order_id, 1) = 'C' then article_price end) as article_priceC
from main
group by order_id;