PostgreSQL return 多行具有 DISTINCT,但每秒列只有最新日期
PostgreSQL return multiple rows with DISTINCT though only latest date per second column
假设我有以下数据库 table(日期被截断仅作为示例,两个 'id_' 前缀列与其他 tables 连接)...
+-----------+---------+------+--------------------+-------+
| 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
所有描述,但同时只有 最近 年的描述?所以我需要数据库查询 return 上面示例数据的第一行和最后一行;第二个没有 returned,因为最后一行的日期较晚。
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;
Postgres 有一个叫做 distinct on
的东西。这通常比使用 window 函数更有效。因此,另一种方法是:
SELECT distinct on (description) id, date, description
FROM inventory
ORDER BY description, date desc;
假设我有以下数据库 table(日期被截断仅作为示例,两个 'id_' 前缀列与其他 tables 连接)...
+-----------+---------+------+--------------------+-------+
| 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
所有描述,但同时只有 最近 年的描述?所以我需要数据库查询 return 上面示例数据的第一行和最后一行;第二个没有 returned,因为最后一行的日期较晚。
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;
Postgres 有一个叫做 distinct on
的东西。这通常比使用 window 函数更有效。因此,另一种方法是:
SELECT distinct on (description) id, date, description
FROM inventory
ORDER BY description, date desc;