requisition_id handler_datetime hand_time
151 2013-12-19 16:39:25 2013-12-19
151 2013-12-19 14:47:52 2013-12-19
151 2013-12-19 14:32:52 2013-12-19
150 2013-12-19 14:47:52 2013-12-19
150 2013-12-16 14:32:52 2013-12-16
150 2013-12-16 16:39:25 2013-12-16
150 2013-12-19 14:47:52 2013-12-19
150 2013-12-16 14:35:52 2013-12-16
需要按照requisition_id分组,然后根据handler_datetime的年月日来分组,按时间逆序排列,取出每个分组最新一条数据,要求MySQL实现。
最终需要得到的结果:
requisition_id handler_datetime hand_time
151 2013-12-16 16:39:25 2013-12-19
150 2013-12-19 14:47:52 2013-12-19
150 2013-12-16 16:39:25 2013-12-16
3 个解决方案
#1
select requisition_id,handler_datetime,hand_time
from table group by requisition_id,date_format(handler_datetime,'%Y-%m-%d') order by hand_time desc ;
#2
select requisition_id,max(handler_datetime) as handler_datetime, hand_time from table_name group by requisition_id,hand_time order by hand_time desc;
#3
#其实直接group by requisition_id + max(handler_datetime)即可实现
select requisition_id ,max(handler_datetime),hand_time from table_name group by requisition_id
#或
select requisition_id ,max(date_format(handler_datetime,'%Y-%m-%d')),hand_time from table_name group by requisition_id #如果是字符串类型 直接使用,如果是时间戳 需要转换
#1
select requisition_id,handler_datetime,hand_time
from table group by requisition_id,date_format(handler_datetime,'%Y-%m-%d') order by hand_time desc ;
#2
select requisition_id,max(handler_datetime) as handler_datetime, hand_time from table_name group by requisition_id,hand_time order by hand_time desc;
#3
#其实直接group by requisition_id + max(handler_datetime)即可实现
select requisition_id ,max(handler_datetime),hand_time from table_name group by requisition_id
#或
select requisition_id ,max(date_format(handler_datetime,'%Y-%m-%d')),hand_time from table_name group by requisition_id #如果是字符串类型 直接使用,如果是时间戳 需要转换