PostgreSQL使用DISTINCT返回多行,但只返回最新的每秒日期列

Joh*_*ohn 3 sql postgresql select greatest-n-per-group

让我说我有以下数据库表(仅截取日期,两个'id_'preix列与其他表连接)...

+-----------+---------+------+--------------------+-------+

| 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 |
+-----------+---------+------+--------------------+-------+
Run Code Online (Sandbox Code Playgroud)

...我有一个像下面这样的查询......

SELECT id, date, description FROM inventory ORDER BY date ASC;
Run Code Online (Sandbox Code Playgroud)

我如何SELECT描述所有描述,但每次仅描述一次,同时仅描述该描述的最新年份?所以我需要数据库查询来返回上面的示例数据中的第一行和最后一行; 第二行没有返回,因为最后一行有更晚的日期.

Gor*_*off 6

Postgres有一些东西叫做distinct on.这通常比使用窗口函数更有效.所以,另一种方法是:

SELECT distinct on (description) id, date, description
FROM inventory
ORDER BY description, date desc;
Run Code Online (Sandbox Code Playgroud)


Mur*_*nik 5

row_number window function应该做的伎俩:

SELECT  id, date, description 
FROM    (SELECT id, date, description, 
                ROW_NUMBER() OVER (PARTITION BY description 
                                   ORDER BY date DESC) AS rn
         FROM   inventory) t
WHERE    rn = 1
ORDER BY date ASC;
Run Code Online (Sandbox Code Playgroud)