我有总价和数量清单。我想根据这些数据计算每件商品的价格。
例如if:总价为200
我有:
item name quantity
item_a 100
item_b 2
可能的解决方案是:
item name quantity price
item_a 100 1
item_b 2 50
,因为:
100 * 1 + 2 * 50 = 200
使用Python,java或任何编程语言循环和转移非常简单......
我无法将此逻辑应用于Postgresql查询。
我有:
shipment
表:
shipmnetid price
5 200
7 10
shipmentitems
表:
siid shipmentid itemid qty
1 5 700 100
2 5 701 2
3 7 1
我需要编写一个将生成(for shipmentid=5
)的查询:
itemid quantity price
700 100 1
701 2 50
价格未保存在表格中,查询的每次运行都可以生成不同的价格......(或者通过siid订购它然后它将始终是相同的值)
我知道这听起来很奇怪,这是关于他们的价格未知的非常旧的物品,所以我只有货物的总价值,我需要“重建”物品价格。
我该怎么做?
答案 0 :(得分:1)
如果正如你在评论中所说的那样,任何解决方案都是好的,那么只需采用平均价格:
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