1,MySql5.7版本

SELECT * FROM
(
SELECT a.*,
@rn:= CASE WHEN @securityid = sxbelecid THEN @rn + 1 ELSE 1 END AS rn,
@securityid:= sxbelecid as sxbelecidf

FROM
(SELECT * from table WHERE nowtime >= ‘2020-02-01 00:00:00’
AND nowtime <= ‘2020-02-01 01:00:00’ ORDER BY sxbelecid, nowtime DESC) a
,(SELECT @rn=0, @securityid=0) b
)a WHERE rn =1
说明:sxbelecid是根据这个字段分组,nowtime是根据这个字段排序 ,rn是取每个sxbelecid的最新的一条记录

2,MySQL5.7以下版本

select * from (select H.id,H.time,H.number,H.sex,H.user_id,@rownum:=@rownum+1 rownum,
if(@pdept=H.user_id,@rank:=@rank+1,@rank:=1) as rank,
@pdept:=H.user_id
from (
select id,time,number,sex,user_id from test order by time desc
) H ,(select @rownum :=0 , @pdept := null ,@rank:=0) a) t WHERE rank=1
说明:user_id是根据这个字段分组,time是根据这个字段排序,rank等于1是取每个user_id的最新的一条记录

参考:http://www.manongjc.com/detail/15-olzniivkfsodftm.html

————————————————
版权声明:本文为CSDN博主「雨细昆孤飞」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/it_xiaoqiao/article/details/108492342