如何在mysql中为每个客户选择最后的订单日期

时间:2016-08-16 16:44:05

标签: mysql sql database group-by

table_customers(customer_id, customer_name)
table_orders(customer_id, order_id, order_datetime)

我想为每个last order date获取customer。如果客户没有为她下订单00-00-0000

这是我的查询。

select C.customer_id , date(O.order_datetime) 
from table_customers C 
INNER JOIN table_orders O ON C.customer_id = O.customer_id 
group by O.customer_id order by O.order_datetime desc limit 1;

它仅返回最后一个客户的最后订单日期。

如何获得所有客户的最后订单日期?

2 个答案:

答案 0 :(得分:3)

你好结帐我的sql下面..

select coalesce(max(o.order_datetime), '0000-00-00 00:00:00') as last_order_date, c.customer_id 
from table_orders as o
right join table_customers as c on o.customer_id = c.customer_id
group by c.customer_id
order by c.customer_id;

这可能会对你有帮助。

样本结果如下。

enter image description here

答案 1 :(得分:0)

您可以执行以下操作

SELECT customer_table.*, orders.order_date FROM customer_table left join (SELECT customer_id, order_date FROM (SELECT tmp.* from  order_table ORDER BY order_date DESC ) as tmp GROUP BY tmp.customer_id) as orders on orders.customer_id= customer_table.id where order.order_date NOT NULL