mysql實現分組排名
在oracle中,可以使用row_number() over(partition by ... order by ...)
的方法實現分組排名,在mysql
中並不提供類似方法,但也可以實現這樣的功能
實例演示:
實例1:實現分組排名-單字段
# mysql實現分組排名-單字段
select
t.member_id,# 分組字段
t.order_date,# 排名字段
# 排名計算邏輯
case
when @num = t.member_id then @rank:=@rank+1
else @rank:=1
end rownum,
# 分組字段臨時參數的設置一定要放到排名計算邏輯後面
@num:=t.member_id
from
# 這個r表是必須要的,先做變量初始化,否則第一次查詢的時候會有問題
(select @rank:=0,@num:=0 from dual) r,
bi_t_pro_z_achievement_detail t
order by
t.member_id,# 分組字段
t.order_date # 排名字段
上述實例中,我的主表是bi_t_pro_z_achievement_detail
,實現了根據member_id
進行分組,然後根據order_date
從小到大排名
實例2:實現分組排名-多字段
# mysql實現分組排名-多字段
select
t.store_id,# 分組字段1
t.member_id,# 分組字段2
t.order_date,# 排名字段1
# 排名計算邏輯
case
when @num1 = t.store_id and @num2 = t.member_id then @rank:= @rank+1
else @rank:=1
end rank,
# 分組字段臨時參數的設置一定要放到排名計算邏輯後面
@num1:=t.store_id as v_num1,# 分組字段臨時參數1
@num2:=t.member_id as v_num2# 分組字段臨時參數2
from
# 這個r表是必須要的,先做變量初始化,否則第一次查詢的時候會有問題
(select @num1:=0,@num2:=0,@rank:=0 from dual) r,
bi_t_pro_z_achievement_detail t # 主表
order by
t.store_id,# 分組字段
t.member_id, # 分組字段
t.order_date desc # 排名字段
上述實例中,我的主表是bi_t_pro_z_achievement_detail
,實現了根據store_id
和member_id
進行分組,然後根據order_date
從大到小排名
實例3:實現分組排名-多字段
# mysql實現分組排名-多字段:排名相等則同名
select
t.store_id,# 分組字段1
t.member_id,# 分組字段2
t.commodity_cost,# 排名字段1
# 排名計算邏輯
case
when @num1 = t.store_id and @num2 = t.member_id and @num3 = t.commodity_cost then @rank:=@rank+0
when @num1 = t.store_id and @num2 = t.member_id then @rank:= @rank+1
else @rank:=1
end rank,
# 分組字段臨時參數的設置一定要放到排名計算邏輯後面
@num1:=t.store_id as v_num1,# 分組字段臨時參數1
@num2:=t.member_id as v_num2,# 分組字段臨時參數2
@num3:=t.commodity_cost as v_num3 # 排名字段臨時參數1:這個參數主要用來判斷同名的情況
from
# 這個r表是必須要的,先做變量初始化,否則第一次查詢的時候會有問題
(select @num1:=0,@num2:=0,@num3:=0,@rank:=0 from dual) r,
bi_t_pro_z_achievement_detail t # 主表
order by
t.store_id,# 分組字段
t.member_id, # 分組字段
t.commodity_cost desc # 排名字段
上述實例中,我的主表是bi_t_pro_z_achievement_detail
,需求是需要根據store_id
和member_id
進行分組,然後根據commodity_cost
從大到小排名,但是這裏會有個問題,因爲同一個store_id
不同member_id
的commodity_cost
有可能會一樣,就像我們平時考試,同一個班的不同人,可能兩個人的總分是一樣的高的,這時候兩個人應該是並列的名次,而不是一前一後,所以這個方法實現了類似oracle的rank() over(partition by ... order by ...)
的功能