查询订单表并获取每个客户的最新记录

时间:2015-07-24 23:57:17

标签: mysql

我有一张订单表。客户可以多次出现。 orderID列是自动增量。我需要运行一个查询来获取每个客户的最新订单,但我需要获取最新订单的orderID,orderDate和orderProduct。

customer    orderID     orderDate       orderProduct
1           1           2015-01-01      shoes
1           2           2015-02-01      food
1           3           2015-03-01      drinks
2           4           2015-01-01      water
2           5           2015-04-01      beer
3           6           2015-01-01      pizza
3           7           2015-07-01      pasta

我原本希望使用:

select orders.*, max(orderDate) as latestOrder from orders group by customer

但这似乎并不能满足我的需要。

我正在寻找的结果将是:

customer    orderID     orderDate       orderProduct
1           3           2015-03-01      drinks
2           5           2015-04-01      beer
3           7           2015-07-01      pasta

2 个答案:

答案 0 :(得分:3)

在这里使用某种自我加入

select t1.* from orders t1
inner join (
  select customer, max(orderDate) as latestOrder from orders  
  group by customer
) t2
where t1.customer = t2.customer AND t1.orderDate = t2.latestOrder

答案 1 :(得分:0)

WITH CTE AS(
   SELECT customer,orderID,orderDate,orderProduct,
       ROW_NUMBER()OVER(PARTITION BY customer ORDER BY orderID desc)
   FROM tab
)
select * from tab where orderid in (
select  max(orderid) as maxorder from cte group by customer)

这适用于任何支持CTE的RDBMS。继承人demo