在SQL中用join和group by添加两个总和

时间:2018-12-06 05:55:24

标签: mysql sql database

SELECT t1.id, t1.name,SUM(t3.points), SUM(t2.points)
FROM app_users t1
LEFT JOIN loyalty_points_redeem t3 ON t3.app_user_id = t1.id
LEFT JOIN loyalty_points_gain t2 ON t2.app_user_id = t1.id    
GROUP BY t1.id

我想从表中先计算出一个特定的i的总和是可以的,但是另一个是不正确的,我是sql的新手,如何解决这个问题,请帮忙

2 个答案:

答案 0 :(得分:0)

您可以在group by子句中添加t1.name来尝试以下操作

SELECT t1.id, t1.name,SUM(t3.points), SUM(t2.points)
FROM app_users t1
LEFT JOIN loyalty_points_redeem t3 ON t3.app_user_id = t1.id
LEFT JOIN loyalty_points_gain t2 ON t2.app_user_id = t1.id    
GROUP BY t1.id,t1.name

答案 1 :(得分:0)

在GROUP BY之外看不到任何问题

SELECT t1.id, t1.name,SUM(t3.points), SUM(t2.points)
FROM app_users t1
LEFT JOIN loyalty_points_redeem t3 ON t3.app_user_id = t1.id
LEFT JOIN loyalty_points_gain t2 ON t2.app_user_id = t1.id    
GROUP BY t1.id, t1.name