mysql先分組再排序的sql語句實現
阿新 • • 發佈:2018-11-11
最近專案中有一個需求, 需要先分組,再排序的功能。 搞了好久,經過敏大大(後臺兄弟)指導, 終於搞出來了,分享給大家(demo)。
一、 例子
學生資訊表
需求: 獲取每個學生同一科(type)下的歷史最高分數及相關資訊。
如, Bob同學語文這科,歷史最高分數是123 第一時間想到
sql:
?1 |
select *
from
t_test
group
by
name
, type
order
by
score
desc
;
|
結果:
?1 2 3 |
發現,並不能滿足我們需求。
原因: 先分組了, 然後排序不是我們期望的。
我們希望, 先排序出最高分, 然後分組,每個取一條。
|
4. 換個思路, 用max來找出分數最高
sql:
?1 |
select
*,
max
(score)
as
max_score
from
t_test
group
by
name
, type;
|
結果:
5. 然後用right join 關聯主表, 找出全量資訊
sql:
?1 2 3 |
select
a.*
from
t_test
as
a
right
join
(
select
name
, type,
max
(score)
as
max_score
from
t_test
group
by
name
, type)
as
b
on
a.
name
= b.
name
and
a.type = b.type
and
a.score = b.max_score
order
by
b.
name
, b.type;
|
結果:
二、 總結
通過max(), min()可以實現先排序後分組的功能; 用right join 可以獲取全量資訊; group by中的欄位, select才能用, 如name, type; 同理可以實現:最小分數的同學資訊和除了最高分外其它的資訊(差集), 歡迎交流學習。