简体   繁体   中英

how to use a column value in postgresql

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

i want to find the difference between weight of same order_item_id have different

order_status

i want output like

 order_item_id   order_status  weight   error 
    158871745     "return"      0.5      0.2
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;

其中tabletable的实际名称。

One method uses window functions:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM