【发布时间】:2015-12-02 20:14:15
【问题描述】:
+-------+----------------------+----------+------------------+
| isbn | book_container_id | shelf_id | update_time |
+-------+----------------------+----------+------------------+
| 555 | 6 | shelf100 | 11/15/2015 19:10 |
| 123 | 1 | shelf1 | 11/28/2015 8:00 |
| 555 | 4 | shelf5 | 11/28/2015 9:10 |
| 212 | 2 | shelf2 | 11/29/2015 8:10 |
| 555 | 6 | shelf9 | 11/30/2015 22:10 |
| 321 | 8 | shelf7 | 11/30/2015 8:10 |
| 555 | 4 | shelf33 | 12/1/2015 7:00 |
+-------+----------------------+----------+------------------+
假设我有一个类似上面的表 (PostgreSQL),名为 bookshelf_configuration。如果给我一个 ISBN 和一个时间戳,我希望能够为 isbn 和 book_container_id 的每个唯一组合找到最接近(仅之前)的记录。
所以如果我正在查看isbn'555',时间戳为'12/1/2015 7:00',我应该返回:
+-------+----------------------+----------+------------------+
| isbn | book_container_id | shelf_id | update_time |
+-------+----------------------+----------+------------------+
| 555 | 6 | shelf9 | 11/30/2015 22:10 |
| 555 | 4 | shelf33 | 12/1/2015 7:00 |
+-------+----------------------+----------+------------------+
我的 SQL 知识非常基础。如果我只需要考虑 isbn,我就有一个可以使用的查询,但我需要一些帮助来了解如何为 (isbn, book_container_id) 组合执行此操作。
【问题讨论】:
标签: sql postgresql greatest-n-per-group