You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL:查询每个客户最新订单的状态

客户最新订单状态查询方案

数据库表结构与数据

Customer表

idname
1Bob
2James

CustomerOrder表

idcustomeramountstatus
111001
21831
314322
42583
52332
63101

OrderStatus表

iddescription
1pending
2completed
3cancelled

查询需求

编写SQL语句,展示每个客户最新订单(订单id最大的记录)的状态,预期结果如下:

预期结果

customerlatest_order_status
12
22
31

实现方案

方法一:使用窗口函数(通用型强)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 23:30:49