假设我有以下数据库表(日期被截断仅作为示例,两个“id_”前缀列与其他表连接)...
+-----------+---------+------+--------------------+-------+
| id_table1 | id_tab2 | date | description | price |
+-----------+---------+------+--------------------+-------+
| 1 | 11 | 2014 | man-eating-waffles | 1.46 |
+-----------+---------+------+--------------------+-------+
| 2 | 22 | 2014 | Flying Shoes | 8.99 |
+-----------+---------+------+--------------------+-------+
| 3 | 44 | 2015 | Flying Shoes | 12.99 |
+-----------+---------+------+--------------------+-------+
...我有如下查询...
SELECT id, date, description FROM inventory ORDER BY date ASC;
我如何SELECT
所有描述,但同时只有最近 年的描述?所以我需要数据库查询从上面的示例数据中返回第一行和最后一行;第二个没有返回,因为最后一行的日期更晚。
最佳答案
Postgres 有一个叫做 distinct on
的东西。这通常比使用窗口函数更有效。因此,另一种方法是:
SELECT distinct on (description) id, date, description
FROM inventory
ORDER BY description, date desc;
关于sql - PostgreSQL 返回带有 DISTINCT 的多行,尽管每秒只有最新的日期列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27829110/