国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > MySQL > 正文

mysql獲取分組后每組的最大值實例詳解

2024-07-24 12:51:40
字體:
來源:轉載
供稿:網友

 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;

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

您可能感興趣的文章:

mysql列轉行以及年月分組實例Mysql利用group by分組排序MYSQL每隔10分鐘進行分組統計的實現方法mysql使用GROUP BY分組實現取前N條記錄的方法MySQL分組查詢Group By實現原理詳解詳解MySQL中的分組查詢與連接查詢語句mysql 將字段time按天/月/年分組mysql分組取每組前幾條記錄(排名) 附group by與order by的研究
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 灵川县| 祁东县| 晋江市| 永登县| 昆山市| 繁峙县| 镇远县| 濉溪县| 龙胜| 万安县| 丰顺县| 鄱阳县| 文水县| 任丘市| 黄陵县| 津市市| 兰州市| 太和县| 怀柔区| 常德市| 来凤县| 涪陵区| 翼城县| 陵川县| 晋江市| 德惠市| 江山市| 卢湾区| 泰州市| 浙江省| 沙湾县| 留坝县| 东阿县| 五大连池市| 肃宁县| 山东省| 梅河口市| 广东省| 巴东县| 海伦市| 朝阳市|