MySQL組內排序取最大值你是怎麼用的呢

2021-10-02 01:10:28 字數 897 閱讀 4559

​開發的小童鞋一般都知道,經常會因為業務的關係求取一些分組的最大值,比如:按照name分組求取不同姓名no的最大值

表 test

±—±---±------+

| id | no | name |

±—±---±------+

| 1 | 1 | mike |

| 2 | 2 | john |

| 3 | 3 | wyett |

| 4 | 4 | herry |

| 5 | 5 | mike |

±—±---±------+

錯誤sql:

select id,max(no),name from test group by test

我們都知道 group by預設取的是排序後的第乙個值,最大值no的name

正確的sql:

第一種:

select id,no,name

from

test as a

where

no = (

select max(no)

from test as b

where a.name = b.name

這種效率快 先查出最大值no然後自連線 得到的值 就是最大值對應法人id,no,name

第二種:

select id,max(no),name

from(

select id ,name,no

from

test

gruop by

name

order by

no desc – 一定是要倒敘排序

) a這種最簡單

這是分組之後按照no最大值倒敘排序的,這樣 第一行的值就是最大值的no,id,name根據group by預設取第一行

mysql 取組內最值記錄

功能要求和以前的一片文章類似 hive取組內最值 在新的工作環境中,使用的資料庫是mysql 5.5版本。不支援開窗函式的使用 因此在解決這個問題的時候需要新的思路。我最欽佩的方法當屬此文 mysql去重保留最大的那條記錄 取最新的記錄 文章使用了自關聯的方法。關聯條件是組名相等,最值列採用不等關係...

mysql 取最大值列的問題

需求 查詢 更新某列 id 最大值的行.嘗試1 select from table where id max select max id from table 可以通過 update table set name new name where id max select max id from ta...

oracle中分組排序並取最大值

最近工作中需要聯合查詢幾個表中的資料,並且需要分組查詢並取得每個組中的最大值,使用到了乙個之前沒有用過的oracle函式,分組排序函式。分組排序函式可以滿足以下需求 1 要求取出按field1分組後,並在每組中按照field2排序 2 亦或更加要求取出1中已經分組排序好的前多少行的資料 分組排序函式...