【发布时间】:2015-11-17 23:37:19
【问题描述】:
我有两个 Postgres 表(实际上,不止于此,但出于问题的目的进行了简化)- 一个是客户订购的产品的记录,另一个是每个客户价格的历史记录和他们购买的日期生效。像这样的:
'订单'表
customer_id | timestamp | quantity
------------+---------------------+---------
1 | 2015-09-29 16:01:01 | 5
1 | 2015-10-23 14:33:36 | 3
2 | 2015-10-19 09:43:02 | 7
1 | 2015-11-16 15:08:32 | 2
'价格'表
customer_id | effective_time | price
------------+---------------------+-------
1 | 2015-01-01 00:00:00 | 15.00
1 | 2015-10-01 00:00:00 | 12.00
2 | 2015-01-01 00:00:00 | 14.00
我正在尝试创建一个查询,该查询将返回该客户在下订单时的每个订单及其单价,如下所示:
想要的结果
customer_id | quantity | price
------------+----------+------
1 | 5 | 15.00
1 | 3 | 12.00
2 | 7 | 14.00
1 | 2 | 12.00
这基本上是我想要的,但我知道您不能在内部查询中引用外部查询,而且我无法弄清楚如何重构:
SELECT
o.customer_id,
o.quantity,
p.price
FROM orders o
INNER JOIN (
SELECT price
FROM prices x
WHERE x.customer_id = o.customer_id
AND x.effective_time <= o.timestamp
ORDER BY x.effective_time DESC
LIMIT 1
) p
;
谁能提出最好的方法来完成这项工作?
【问题讨论】:
-
如果使用
join lateral,可以在join查询中引用orders表。
标签: sql postgresql