获取每个唯一 ID 的最大列值

Get the max column value for each unique ID

我有两个 table,一个 customersorders table。

customers table 包含每个客户的唯一 ID。它包含 1141 个条目。

orders table 包含许多带有 customerIDdate 的条目。

我正在尝试查询我的数据库和 return 客户列表以及来自订单列表的 max(date)

SELECT *
FROM customers
INNER JOIN
(
    SELECT CustomerID, max(date) as date
    FROM orders
    GROUP BY CustomerID
) Sub1
ON customers.id = Sub1.CustomerID
INNER JOIN orders
ON orders.CustomerID = Sub1.CustomerID
AND orders.date = Sub1.Date

然而,此查询 returning 1726 行而不是 1141 行。这是从哪里得到额外的?

我认为这是因为 ORDERS table 多次包含相同的 customerID,所以当您加入 table 与 CUSTOMERS 时,每个 CUSTOMER.id 匹配多行 ORDERS。

;with cte as
(
  select CustomerID, orderdate
      , rn = row_number() over (partition by customerID order by orderdate desc)
from orders
)

select c.*, cte.orderdate
from customer c
 join cte on cte.customerID = c.customerid 
where rn =1 -- This will limit to latest orderdate

问题是有平局

对于给定的客户,有些客户每天会下多个订单。因此,有时有些人可能会在他们的最大日期下达多个订单。

要解决此问题,您需要使用 MAX() 或某些 在订单 table 中始终唯一的列(或至少在给定日期)。如果您可以依赖订单 table:

中的 auto-increment 主键,这很容易
SELECT *
FROM customers
INNER JOIN
(
    SELECT CustomerID, max(orderid) as orderid as date
    FROM orders
    GROUP BY CustomerID
) Sub1
ON customers.id = Sub1.CustomerID
INNER JOIN orders
ON orders.CustomerID = Sub1.CustomerID
AND orders.orderid = Sub1.orderid

这假设 orderid 在 lock-step 中随着日期的增加而增加。也就是说,您永远不会收到具有更大 auto-inc ID 但更早日期的订单。如果您允许不按时间顺序输入数据,例如back-dating 个订单。