简体   繁体   English

获取每组的最新记录 - mysql(按最大日期/最大主键)

[英]Get latest record in each group - mysql (by max date/max primary key)

id ID orderid订单号 assignedto分配给 date日期
101 101 2001 2001年 1400 1400 11, June 2020 2020 年 6 月 11 日
102 102 2001 2001年 1560 1560 16, June 2021 2021 年 6 月 16 日
103 103 3450 3450 1560 1560 19, June 2020 2020 年 6 月 19 日

Desired result -期望的结果 -

id ID orderid订单号 assignedto分配给 date日期
102 102 2001 2001年 1560 1560 16, June 2021 2021 年 6 月 16 日
103 103 3450 3450 1560 1560 19, June 2020 2020 年 6 月 19 日

For each order id I want the last person who was assigned to the order.对于每个订单 ID,我想要分配给订单的最后一个人。

My current query retrieves data by joining other fields as -我当前的查询通过加入其他字段来检索数据 -

select y.id, x.orderid, assigneedto, date from (select id, orderid, date as date_rejected 
from tbl1
where status = 'A') x 
left join tbl1 as y
on x.orderid = y.orderid 
where y.status = 'B' and x.date_rejected > y.date

I tried using max(date) and grouping by orderid but the results are incorrect.我尝试使用max(date)并按orderid 分组,但结果不正确。

It's very complicated to understand what do you mean as tables are different from query, but I guess OVER PARTITION BY function will definitely resolve your issue, even without left join.由于表与查询不同,理解您的意思是非常复杂的,但我想 OVER PARTITION BY function 肯定会解决您的问题,即使没有左连接。 https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM