我正在制定一种汽车统计解决方案,需要每行驶一公里就收费一次。
我有下表:
table: cars
columns: car_id, km_driven
table: pricing
columns: from, to, price
我cars
表中的内容可以是:
car_id, km_driven
2, 430
3, 112
4, 90
我pricing
桌子上的内容可以是:
from, to, price
0, 100, 2
101, 200, 1
201, null, 0.5
这意味着前100公里的价格为每公里2美元,接下来的100公里的价格为每公里1USD,以上所有价格为0.5美元。
有没有一种逻辑和简单的方法来为我的过cars
孔计算成本PostgreSQL
?
因此,如果acar
驱动了ex。201,那么价格将是100x2 + 100x1 + 0.5
,而不是简单地201x0.5
。
我将查询写为:
select c.car_id, c.km_driven,
sum(( least(p.to_km, c.km_driven) - p.from_km + 1) * p.price) as dist_price
from cars c join
pricing p
on c.km_driven >= p.from_km
group by c.car_id, c.km_driven;
这是db <> fiddle。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句