如何在postgresql中使用列值

时间:2015-03-24 11:13:36

标签: sql postgresql

order_item_id   order_status   weight
158871745        "delivered"       0.3
158032756        "delivered"       0.3
158871745        "return"          0.5

我想找到相同order_item_id的权重之间的差异有不同

ORDER_STATUS

我想输出

 order_item_id   order_status  weight   error 
    158871745     "return"      0.5      0.2

2 个答案:

答案 0 :(得分:1)

select t1.weight-t2.weight from table as 't1' join table as 't2' on t1.order_item_id=t2.order_item_id where t1.order_status!=t2.order_status;

其中table是表的实际名称。

答案 1 :(得分:0)

一种方法使用窗口函数:

select t.*,
       (case when min(order_status) over (partition by order_item_id) <>
                  max(order_status) over (partition by order_item_id)
             then max(weight) over (partition by order_item_id) - 
                  min(weight) over (partition by order_item_id)
        end) as weightdiff
from table t;