MySQL(1)------group by 分組 取最大值

首先表結構

create table sysstudentlibrarypool
(
  id       int auto_increment primary key,
  score    int          null,
  time     varchar(255) null,
  count    int          null,
  classify int          null,
  stuId    int          null,
  lpId     int          null,
)
  • id爲主鍵
  • score是分數
  • time是時間 (yyyy-MM-dd)
  • count是次數
  • classify是類別
  • stuId是個外鍵指向學生表的學生id
  • lpId是個外鍵指向關卡id

這張表用於保存學生每次完成關卡的分數

需求就是取每個學生在指定關卡的最大分數
加粗的就是與需求有關的字段

先排序後分組

select *
from (
       select *
       from sysstudentlibrarypool
       order by score desc 
     ) t
group by stuId

先根據分數排序,再根據 stuId 和 lpId 分組。
看這個邏輯貌似是很有道理
但執行了之後卻好像並沒有達到我所要的需求
Exler
雖然 學生與關卡分組了但是,並沒有取到最大做題分數啊!

加個max()

select
  id,
  max(score) as score,
  time,
  count,
  classify,
  stuId,
  lpId
from (
       select *
       from sysstudentlibrarypool
       order by score desc
     ) t
group by stuId, lpId

Exler
額,的確是顯示了最大的分數了,但是好像記錄是對不上的
只顯示了最大的分數其他的字段並不是對應分數的

實現思路

唉,找不到靠譜的輪子只能自己上了

select
  id,
  max(score) as score,
  time,
  count,
  classify,
  stuId,
  lpId
from sysstudentlibrarypool
where 1 = 1 and stuId in (select distinct (stuId)
                          from sysstudentlibrarypool
                          where 1 = 1)
group by lpId, stuId
order by score desc;

Exler
主要實現思路:
1. 子查詢中取 學生id(有條件時取單個,沒有條件時取所有的學生id)
2. 根據關卡 學生id 分組,然後進行分數排序(取分數最大的),也可以添加各種條件(指定關卡,指定時間戳等)
3. 就能查詢每關的每個學生的最大分數

這樣每個where 1 = 1後面都能加上查詢條件了。

積累

    1.
group by
order by

這裏的排序是對分組後的數據排序
2. 突然有點明白group by的作用了

對指定的字段進行分組,然後根據需求顯示,想要的字段,比如每組中max(某字段)

不知道怎麼的以前總理解爲 分組並顯示每組中所有記錄。。。。。


這裏只是提供一下自己的思路,也請大神給出更好的實現,相互學習,謝謝。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章