PostgreSQL:查询每个客户最新订单的状态
客户最新订单状态查询方案
数据库表结构与数据
Customer表
| id | name |
|---|---|
| 1 | Bob |
| 2 | James |
CustomerOrder表
| id | customer | amount | status |
|---|---|---|---|
| 1 | 1 | 100 | 1 |
| 2 | 1 | 83 | 1 |
| 3 | 1 | 432 | 2 |
| 4 | 2 | 58 | 3 |
| 5 | 2 | 33 | 2 |
| 6 | 3 | 10 | 1 |
OrderStatus表
| id | description |
|---|---|
| 1 | pending |
| 2 | completed |
| 3 | cancelled |
查询需求
编写SQL语句,展示每个客户最新订单(订单id最大的记录)的状态,预期结果如下:
预期结果
| customer | latest_order_status |
|---|---|
| 1 | 2 |
| 2 | 2 |
| 3 | 1 |
实现方案
方法一:使用窗口函数(通用型强)
SELECT customer, status AS latest_order_status FROM ( SELECT customer, status, ROW_NUMBER() OVER (PARTITION BY customer ORDER BY id DESC) AS row_num FROM CustomerOrder ) AS order_ranked WHERE row_num = 1;
方法二:使用关联子查询
SELECT co.customer, co.status AS latest_order_status FROM CustomerOrder co WHERE co.id = ( SELECT MAX(id) FROM CustomerOrder WHERE customer = co.customer );
内容的提问来源于stack exchange,提问作者ranalto
相关产品推荐
相关产品推荐

