3

我有两个表 - 客户和订单。每个客户将有 1..n 个订单。它们与 Orders 表中的 Customers 表的外键有关系。到目前为止,DB 101 也是如此。

我需要一个查询,该查询将为每个客户返回一行,以及该客户最新订单的日期和订单 ID。所有客户至少有一份订单。我可以使用函数轻松完成此操作,但我更喜欢在 SQL 中执行此操作。

4

2 回答 2

3

In case of auto incremented ID-s, and no variance with dates, the solution is that simple:

SELECT c.*, o.*
FROM Customer c 
JOIN (SELECT max(id) as order_id, customer_id 
      FROM Order GROUP BY curtomer_id) conn on c.id = conn.customer_id
JOIN Order o on o.id = conn.order_id
于 2012-05-17T09:26:00.603 回答
1

你没有说明你的 DBMS,所以我假设一个符合 ANSI 的引擎。

select *
from (
    SELECT c.*, 
           o.*, 
           row_number() over (partition by o.customer_id order by order_date desc) as rn
    FROM Customer c 
      JOIN Order o on o.customer_id = c.id
)
where rn = 1
于 2012-05-17T09:31:57.663 回答