各位用户为了找寻关于Mysql利用group by分组排序的资料费劲了很多周折。这里教程网为您整理了关于Mysql利用group by分组排序的相关资料,仅供查阅,以下为您介绍关于Mysql利用group by分组排序的详细内容

昨天有个需求对数据库的数据进行去重排名,同一用户去成绩最高,时间最短,参与活动最早的一条数据进行排序。我们可以利用MySQL中的group by的特性。

MySQL的group by与Oracle有所不同,查询得字段可以不用写聚合函数,查询结果取得是每一组的第一行记录。

利用上面的特点,可以利用mysql实现一种独特的排序;

首先先按某个字段进行order by,然后把有顺序的表进行分组,这样每组的成员都是有顺序的,而mysql默认取得分组的第一行。从而得到每组的最值。

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 select id, (@rowno := @rowno + 1) as rank,  score,  (C.end_time - C.start_time) as timeConsuming,  start_time,  real_name,  tel,  expiry_code  from (SELECT *   FROM (select *    from t_q_order B    where B.score > 0    and B.tel IS NOT NULL    order by B.score desc,     (B.end_time - B.start_time) asc,     B.start_time asc) as A   group by A.tel   ORDER BY A.score desc,    (A.end_time - A.start_time) asc,    A.start_time asc)  as C,  (select @rowno := 0) t  where (C.end_time - C.start_time) > 5 limit 0,50;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。