Postgresql如何将select列匹配条件?
Postgresql how to select columns where it matches conditions?
我有一个 table 这样的:
inventory_id | customer_id | max
--------------+-------------+---------------------
4497 | 1 | 2005-07-28 00:00:00
1449 | 1 | 2005-08-22 00:00:00
1440 | 1 | 2005-08-02 00:00:00
3232 | 1 | 2005-08-02 00:00:00
3418 | 2 | 2005-08-02 00:00:00
654 | 2 | 2005-08-02 00:00:00
3164 | 2 | 2005-08-21 00:00:00
2053 | 2 | 2005-07-27 00:00:00
我想要 select 行,其中最近的日期和相应的列,这就是我想要实现的:
inventory_id | customer_id | max
--------------+-------------+---------------------
1449 | 1 | 2005-08-22 00:00:00
3164 | 2 | 2005-08-21 00:00:00
我尝试使用聚合,但我需要 inventory_id 和 customer_id 同时出现。
有没有什么方法可以做到这一点?
使用distinct on
:
select distinct on (customer_id) t.*
from t
order by customer_id, max desc;
distinct on
是一个 Postgres 扩展,根据括号中的任何内容,行上 returns。此行基于 order by
-- 排序集中出现的第一个。
SELECT inventory_id, customer_id, max FROM
(SELECT inventory_id, customer_id, max,
ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY max DESC) AS ROWNO
FROM inventory_table) AS A
WHERE ROWNO=1
我有一个 table 这样的:
inventory_id | customer_id | max
--------------+-------------+---------------------
4497 | 1 | 2005-07-28 00:00:00
1449 | 1 | 2005-08-22 00:00:00
1440 | 1 | 2005-08-02 00:00:00
3232 | 1 | 2005-08-02 00:00:00
3418 | 2 | 2005-08-02 00:00:00
654 | 2 | 2005-08-02 00:00:00
3164 | 2 | 2005-08-21 00:00:00
2053 | 2 | 2005-07-27 00:00:00
我想要 select 行,其中最近的日期和相应的列,这就是我想要实现的:
inventory_id | customer_id | max
--------------+-------------+---------------------
1449 | 1 | 2005-08-22 00:00:00
3164 | 2 | 2005-08-21 00:00:00
我尝试使用聚合,但我需要 inventory_id 和 customer_id 同时出现。 有没有什么方法可以做到这一点?
使用distinct on
:
select distinct on (customer_id) t.*
from t
order by customer_id, max desc;
distinct on
是一个 Postgres 扩展,根据括号中的任何内容,行上 returns。此行基于 order by
-- 排序集中出现的第一个。
SELECT inventory_id, customer_id, max FROM
(SELECT inventory_id, customer_id, max,
ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY max DESC) AS ROWNO
FROM inventory_table) AS A
WHERE ROWNO=1