2016-08-16 102 views
0
table_customers(customer_id, customer_name) 
table_orders(customer_id, order_id, order_datetime) 

我想要獲得last order date每個customer。如果客戶沒有爲她訂購任何退貨00-00-0000如何在mysql中選擇每個客戶的最後訂單日期

這是我的查詢。

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; 

它僅爲最後一位客戶返回最後一個訂單日期。

如何獲取所有客戶的最後訂單日期?

+0

刪除'limit 1'? – David

回答

2

喜籤我下面的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

+0

謝謝Avishek。它爲我工作。 –

+0

這是我的榮幸..:D – Avishek

+0

我有一個更多的查詢,類似的路線。我發佈在http://stackoverflow.com/questions/38982167/how-to-select-customers-final-balance-for-all-customer-in-mysql請檢查你是否可以幫助我? –

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 
相關問題