[英]mySQL query: order by group points by sum of join member points
我有2個鏈接的表。 組可以有多個用戶,用戶可以在多個組中。
GROUPS
|id| name |
----------------
|1| Koalas |
|2| Grizzlies |
|3| Hornets |
----------------
USERS
|id| firstName | points |
----------------
|1| Bob | 2
|2| Hans | 4
|3| Jerome | 1
|4| Katy | 6
----------------
GROUP_USER
|id| group_id | user_id |
--------------------------
|1| 1 | 2
|2| 1 | 4
|3| 2 | 1
|4| 2 | 2
|5| 3 | 3
|6| 3 | 4
----------------
現在,我想按組成員的積分對組進行排名。 結果:
GROUP_USER
|rank| group_name | user_points |
-----------------------------------
|1 | Koalas | 10
|2 | Hornets | 7
|3 | Grizzlies | 6
真的不知道如何開始。
select @rank := @rank + 1 as rank, name, user_points
from
(
select g.name,
sum(u.points) as user_points
from groups g
left join group_user gu on gu.group_id = g.id
left join users u on gu.user_id = u.id
group by g.name
order by user_points desc
) tmp
cross join (select @rank := 0) r
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.