相关疑难解决方法(0)

如何有效地获得“最近的对应行”?

我有一个一定很常见的查询模式,但我不知道如何为它编写有效的查询。我想查找与“最近日期不晚于”另一个表的行相对应的表的行。

inventory比如说,我有一张表格,它代表了我在某一天持有的库存。

date       | good | quantity
------------------------------
2013-08-09 | egg  | 5
2013-08-09 | pear | 7
2013-08-02 | egg  | 1
2013-08-02 | pear | 2
Run Code Online (Sandbox Code Playgroud)

和一张表,“价格”说,它保存了某一天的商品价格

date       | good | price
--------------------------
2013-08-07 | egg  | 120
2013-08-06 | pear | 200
2013-08-01 | egg  | 110
2013-07-30 | pear | 220
Run Code Online (Sandbox Code Playgroud)

如何有效地获得库存表每一行的“最新”价格,即

date       | pricing date | good | quantity | price
----------------------------------------------------
2013-08-09 | 2013-08-07   | egg  | 5        | 120
2013-08-09 …
Run Code Online (Sandbox Code Playgroud)

postgresql performance greatest-n-per-group query-performance

68
推荐指数
5
解决办法
13万
查看次数