[英]How display multiple rows in a table with one row in another table as single row
I have two tables. 我有两张桌子。 Table "user" contains user_id, user_name Table "Transactions" contains user_id, transactions 表“user”包含user_id,user_name表“Transactions”包含user_id,transactions
Eg: 例如:
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
I want to display the result as: 我想将结果显示为:
user_name, Total
Ram, 1500*
John, 250
Rahim, 150
How can I do this? 我怎样才能做到这一点?
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
I think you should use LEFT JOIN because it should select user's total (NULL) in any case, even if it's 0 我认为你应该使用LEFT JOIN,因为它应该在任何情况下选择用户的总数(NULL),即使它是0
SELECT u.user_id , SUM(t.transactions) AS total
FROM user AS u JOIN transactions AS t
GROUP BY u.user_id
Try 尝试
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.