sql - 计算回收期
问题描述
我想计算客户达到“回报期”所需的时间。也就是说,当他们有效地在我们的商店花费了足够的钱来抵消该特定客户的广告成本时。
Customers
| id | created_at | acquisition_cost |
| 3 | 2019-03-04 20:24:49 | 39.90 |
Orders
| id | customer_id | created_at | profit |
| 39 | 3 | 2019-04-03 05:39:39 | 19.91 |
| 86 | 3 | 2019-06-03 07:29:18 | 17.39 |
我想知道的是,Postgresql 中是否有一种高效的方法可以找到使客户超过 39.90created_at
的订单(由 订购) 。created_at ASC
acquisition_cost
解决方案
您可以使用累积总和:
select c.*,
sum(o.profit) over (partition by o.customer_id order by o.created_at) as running-profit
from orders o join
customers c
on o.customer_id = c.id;
如果你想要第一次约会,那么:
select distinct on (id) oc.*
from (select c.*, o.created_at as order_created_at,
sum(o.profit) over (partition by o.customer_id order by o.created_at) as running_profit
from orders o join
customers c
on o.customer_id = c.id
) oc
where running_profit >= c.acquisition_cost
order by id, order_created_at
推荐阅读
- java - Firebase GeoFire setlocation 在服务中不起作用
- corda - 运行 deployNodes 时失败
- spring - 计划任务是否应该在每次执行时启动 Spring 应用程序?
- ios - 如何查看应用内购买(自动续订)的购买状态?
- android - 使用 Kotlin 在 Android 中复制文件 Flutter 插件
- javascript - Jquery验证自定义CSS复选框
- mysql - 如何解决 django.db.utils.IntegrityError: (1364, "Field 'name' doesn't have a default value")
- python - 脚本无法生成结果
- sql-server - 完全“镜像”或复制 SQL Server
- javascript - 如何使某些代码仅在某些特定域上运行