Mysql利用group by分组排序

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Mysql利用group by分组排序

wylfll   2020-12-15 我要评论
这篇文章主要为大家详细介绍了Mysql利用group by分组排序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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

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

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

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;

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们