聚合我的行后获取最新的 order_date

Get the latest order_date after aggregation my rows

我有 2 个 table:

有没有办法在不使用相关子查询的情况下,在按订单数排序的单个查询中获取每个客户的所有订单数以及最新的订单日期?

我已经有了这个:

SELECT C.customer_id, O.order_date, COUNT(O.order_id) AS orders_count 
FROM customers AS C
LEFT JOIN orders AS O ON O.customer_id = C.customer_id
GROUP BY C.customer_id
ORDER BY COUNT(O.order_id) DESC, O.order_date DESC 

但是,我只能得到客户第一次下订单的日期。

使用MAX()聚合函数:

SELECT C.customer_id, MAX(O.order_date), COUNT(O.order_id) AS orders_count 
FROM customers C LEFT JOIN
     orders O
     ON O.customer_id = C.customer_id
GROUP BY C.customer_id
ORDER BY COUNT(O.order_id) DESC, MAX(O.order_date) DESC 

如果 mysql 8.0+ 版本和 10.2 的 maria db 允许 row_number() 这将解决您的问题

select * from (SELECT C.customer_id, O.order_date, COUNT(O.order_id) AS orders_count,
 row_number() over(partition  by  C.customer_id order by O.order_date DESC) rn
FROM customers AS C 
LEFT JOIN orders AS O ON O.customer_id = C.customer_id
 group by  C.customer_id, O.order_date
) a where a.rn=1