用户
id | first_name
------+------------
1 | Ann
2 | Heidi
3 | Becky
4 | Steven
5 | Jenny
服务1
id | user_id | fees
------+-------------+-----------
1 | 3 | 267732
2 | 1 | 68647
3 | 2 | 45954
4 | 1 | 44655
5 | 5 | 42957
服务2
id | user_id | fees
------+-------------+-----------
1 | 3 | 2632
2 | 1 | 0
3 | 2 | 4954
4 | 1 | 4355
5 | 5 | 2927
以下是我的结果:
first_name | total_fees
--------------+------------
Becky | 270364
Ann | 117657
Heidi | 50908
Jenny | 45884
Steven | 0
我对此有点新意,但是我在创建查询时遇到了一个小问题,即对总费用最高的用户进行排名。这是我对查询的破解。基本上我想要退回名称和费用。
SELECT first_name, ((SELECT SUM(fees) FROM service1 WHERE service1.user_id = user.id) + (SELECT SUM(fees) FROM service2 WHERE service2.user_id = user.id)) AS total_fees FROM users ORDER BY total_fees DESC NULLS LAST LIMIT 10;
答案 0 :(得分:3)
首先,您需要获得所有用户的总费用:
select u.*, (coalesce(s1.fee, 0) + coalesce(s2.fee, 0)) as total_fee
from users u left join
(select user_id, sum(fees) as fee
from service1
group by user_id
) s1
on u.id = s1.user_id left join
(select user_id, sum(fees) as fee
from service2
group by user_id
) s2
on u.id = s2.user_id;
在Postgres中,您可以使用ANSI标准RANK()
函数对这些函数进行排名(大多数数据库支持此功能,但不支持MySQL:
select u.*, (coalesce(s1.fee, 0) + coalesce(s2.fee, 0)) as total_fee,
rank() over (order by (coalesce(s1.fee, 0) + coalesce(s2.fee, 0))) as therank
from users u left join
(select user_id, sum(fees) as fee
from service1
group by user_id
) s1
on u.id = s1.user_id left join
(select user_id, sum(fees) as fee
from service2
group by user_id
) s2
on u.id = s2.user_id;
答案 1 :(得分:0)
你可以在子查询上left join
:
SELECT first_name, COALESCE(sum1, 0) + COALESCE(sum2, 0)
FROM users u
LEFT JOIN (SELECT user_id, SUM(fees) AS sum1
FROM service1 s1
GROUP BY user_id) ON u.id = s1.user_id
LEFT JOIN (SELECT user_id, SUM(fees) AS sum2
FROM service1 s2
GROUP BY user_id) ON u.id = s2.user_id