饿虎岗资源网 Design By www.oxmxm.com
mysql获取分组后每组的最大值实例详解
1. 测试数据库表如下:
create table test ( `id` int not null auto_increment, `name` varchar(20) not null default '', `score` int not null default 0, primary key(`id`) )engine=InnoDB CHARSET=UTF8;
2. 插入如下数据:
mysql> select * from test; +----+----------+-------+ | id | name | score | +----+----------+-------+ | 1 | jason | 1 | | 2 | jason | 2 | | 3 | jason | 3 | | 4 | linjie | 1 | | 5 | linjie | 2 | | 6 | linjie | 3 | | 7 | xiaodeng | 1 | | 8 | xiaodeng | 2 | | 9 | xiaodeng | 3 | | 10 | hust | 2 | | 11 | hust | 3 | | 12 | hust | 1 | | 13 | haha | 1 | | 14 | haha | 2 | | 15 | dengzi | 3 | | 16 | dengzi | 4 | | 17 | dengzi | 5 | | 18 | shazi | 3 | | 19 | shazi | 4 | | 20 | shazi | 2 | +----+----------+-------+
3. 下面是重点,目的是要按照name分组,然后分组后,获取每组中score分数最多的,sql如下
select a.* from test a inner join (select name,max(score) score from test group by name)b on a. name=b.name and a.score=b.score order by a.name;
当然,上面的最后的order by a.name可以去掉
4. 测试结果如下:
+----+----------+-------+ | id | name | score | +----+----------+-------+ | 3 | jason | 3 | | 6 | linjie | 3 | | 9 | xiaodeng | 3 | | 11 | hust | 3 | | 14 | haha | 2 | | 17 | dengzi | 5 | | 19 | shazi | 4 | +----+----------+-------+
5. 网上很多方法都是错误的,比如如下一些,亲测是不行的
select * from (select * from test order by score desc) t group by name order by score desc limit 4; select score,max(score) from test group by name; select * from test where score in (select max(score) from test group by name); select * from test where score in (select substring_index(group_concat(score order by score desc separator ','),',',1) from test group by name); select * from (select name,score,ROW_NUMBER() over(group by name order by score desc) as rowNum from test) rank where rank.rowNum <=1 order by rank.score desc; select * from( select StoresNo,[CustomerCaseNo],[PaymentsTime], ROW_NUMBER() over(partition by CustomerCaseNo order by [PaymentsTime] desc) as rowNum from BAL_paymentsSwiftInfo where StoresNo='zq00000034') ranked where ranked.rowNum <= 1 order by ranked.CustomerCaseNo, ranked.PaymentsTime desc select * from (select * from test order by score desc) as a group by a.name;
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
饿虎岗资源网 Design By www.oxmxm.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
饿虎岗资源网 Design By www.oxmxm.com
暂无评论...
更新日志
2024年11月15日
2024年11月15日
- 黄乙玲1988-无稳定的爱心肝乱糟糟[日本东芝1M版][WAV+CUE]
- 群星《我们的歌第六季 第3期》[320K/MP3][70.68MB]
- 群星《我们的歌第六季 第3期》[FLAC/分轨][369.48MB]
- 群星《燃!沙排少女 影视原声带》[320K/MP3][175.61MB]
- 乱斗海盗瞎6胜卡组推荐一览 深暗领域乱斗海盗瞎卡组分享
- 炉石传说乱斗6胜卡组分享一览 深暗领域乱斗6胜卡组代码推荐
- 炉石传说乱斗本周卡组合集 乱斗模式卡组最新推荐
- 佟妍.2015-七窍玲珑心【万马旦】【WAV+CUE】
- 叶振棠陈晓慧.1986-龙的心·俘虏你(2006复黑限量版)【永恒】【WAV+CUE】
- 陈慧琳.1998-爱我不爱(国)【福茂】【WAV+CUE】
- 咪咕快游豪礼放送,百元京东卡、海量欢乐豆就在咪咕咪粉节!
- 双11百吋大屏焕新“热”,海信AI画质电视成最大赢家
- 海信电视E8N Ultra:真正的百吋,不止是大!
- 曾庆瑜1990-曾庆瑜历年精选[派森][WAV+CUE]
- 叶玉卿1999-深情之选[飞图][WAV+CUE]