我正在尝试根据用户拥有的积分(金钱)建立排行榜。这些点存储在多个表中,某些用户可能没有给定表中的点。
Table: account
--------------------------
| uid | name | locker |
|-----|---------|--------|
| 1 | Bob | 15 |
| 2 | Dave | 2 |
| 3 | Jim | 5 |
--------------------------
Table: container
------------------------
| account_uid | money |
|-------------|--------|
| 1 | 4 |
| 3 | 1 |
| 3 | 2 |
| 3 | 4 |
------------------------
Table: vehicle
------------------------
| account_uid | money |
|-------------|--------|
| 2 | 2 |
| 2 | 1 |
| 3 | 2 |
------------------------
我希望看到结果输出为 -
Bob 19
Jim 14
Dave 5
请注意,某些人的某些人没有积分。
此代码对我不起作用。它似乎以某种方式重复了点。
SELECT
act.name,
act.uid,
SUM(COALESCE(act.locker,0) + COALESCE(con.money,0) + COALESCE(veh.money,0)) AS total
FROM account as act
LEFT JOIN container as con
ON act.uid = con.account_uid
LEFT JOIN vehicle as veh
ON act.uid = veh.account_uid
Group By act.name
ORDER BY total DESC
答案 0 :(得分:1)
如何一次计算一个总数然后将它们合并为一个?
select account.uid, account.name, sum(tot.Money) as TotalMoney from
(
(select uid, sum(Money) as Money from container
group by uid)
union all
(select uid, sum(Money) as Money from vehicle
group by uid)
) tot
inner join account on
tot.uid = account.uid
group by account.uid