SQL:仅返回每个客户的最新活动

时间:2015-05-26 17:23:07

标签: mysql sql-order-by distinct

我有两个包含链接数据的表。针对个别客户(customer_id)的活动更新。我想返回每个客户最近的活动;

; customer_id(auto_increment) 姓 FIRST_NAME
phone_work

活性; activity_id(auto_increment) data_item_id entered_by 创建日期 笔记

我可以返回整套活动;

SELECT last_name,first_name,date_created,notes,FROM contact JOIN activity ON contact.customer_id = activity.data_item_id;

..但我只想要每个customer_name的最新活动。如果我使用unique,它似乎返回每个customer_name的第一个活动而不是最新的活动。我确定它非常简单,但我还没有找到它。想法?

3 个答案:

答案 0 :(得分:0)

您可以使用MAX(date_created)从联接表中选择正确的行。否则MySQL将加入所有行,或者在GROUP BY的情况下,选择它找到的第一个匹配行。

所以查询将是:

SELECT MAX(date_created) AS date, last_name, first_name, notes
       FROM contact JOIN activity ON contact.customer_id=activity.data_item_id
       ORDER BY customer_id ASC

答案 1 :(得分:0)

  

WITH TempTbl AS ( SELECT MAX(activity_id) activity_id --as it is auto_increment, this should return the most recent record) ,Last_Name ,First_Name ,Date_Created ,Notes FROM Activity JOIN Contact ON Contact.Customer_Id=Activity.Data_Item_Id ) SELECT * FROM TempTbl

如果您仍然有每个客户的多条记录,那么建议将考虑使用RANK()OVER(PARTITION BY ...来选择最近的记录

答案 2 :(得分:0)

还有一个解决方案:

 select temp.* from
 ( 
  SELECT c.last_name last, c.first_name first, a.date_created, a.notes 
  FROM contact c JOIN activity a ON c.customer_id=a.data_item_id
  order by a.date_created desc
 ) temp
 group by temp.last, temp.first;