我有两张桌子。 表“user”包含user_id,user_name 表“交易”包含user_id,transactions
例如:
TABLE USER:
user_id, user_name
1, Ram
2, John
3, Rahim
TABLE Transactions
user_id, transactions
1, 500
1, 300
2, 250
1, 450
3, 100
1, 250
3, 50
我想将结果显示为:
user_name, Total
Ram, 1500*
John, 250
Rahim, 150
我该怎么做?
答案 0 :(得分:2)
SELECT
u.user_name,
SUM(t.transactions) Total
FROM users u
LEFT JOIN transactions t ON t.user_id = u.user_id
GROUP BY t.user_id
我认为你应该使用LEFT JOIN因为它应该在任何情况下选择用户的总数(NULL),即使它是0
答案 1 :(得分:1)
SELECT u.user_id , SUM(t.transactions) AS total
FROM user AS u JOIN transactions AS t
GROUP BY u.user_id
答案 2 :(得分:1)
尝试
SELECT
u.user_id,
sum(t.transactions) as total
FROM
user u
JOIN transactions t ON u.user_id = t.user_id
GROUP BY
u.user_id