简体   繁体   中英

how to perform a mthematical loop in Postgresql?

I have a total price and list of items with quantity. I want to calculate each item price based on that data.

for example if : total price is 200 and I have:

item name    quantity
item_a         100
item_b         2

a possible solution is:

item name    quantity   price
item_a         100       1
item_b         2        50

because:

100 * 1 + 2 * 50 = 200

This is very simple to do with a loop and diversion with Python,java or any programming language...

I'm having trouble to apply this logic to Postgresql query.

I have: shipment table:

shipmnetid  price
    5        200
    7         10

shipmentitems table:

siid  shipmentid   itemid qty
1         5         700   100
2         5         701   2
3         7          1

I need to write a query that will generate (for shipmentid=5 ):

itemid quantity price
 700      100     1
 701       2      50

Price is not saved in table, each run of the query can generate diffrent prices... (or order it by siid and then it will always be same values)

I know this sounds wierd, this is about very old items that their price is unknown, so I only have the total value of the shipment and I need to "rebuid" the item prices.

How can I do that?

If, as you say in the comments, any solution is good then just take the average price:

select shipmentid, itemid, qty, price::real / total_shipment_qty as price
from
    shipment s
    inner join (
        select
            shipmentid,
            itemid,
            qty,
            sum(qty) over(partition by shipmentid) as total_shipment_qty
        from shipmentitems
    ) i using (shipmentid)
;
 shipmentid | itemid | qty |      price       
------------+--------+-----+------------------
          5 |    700 | 100 | 1.96078431372549
          5 |    701 |   2 | 1.96078431372549

http://sqlfiddle.com/#!15/f8168/1

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