SQL 我如何总结一个 has many 关系

SQL how do I sum up a has many relationship

所以我有以下 table,我设法加入用户和成员资格 tables 并且左加入很好,但是我未能成功总结各个客户的总数。

这是我的代码,一对一关联似乎运行良好,但总数的总和似乎没有显示,我做错了什么?是否有不同的方式来总结一对多关联?

SELECT name, membership.userId as customerId, SUM(sales.total) as Total 
FROM users

LEFT OUTER JOIN membership ON membership.userId = users.id
LEFT OUTER JOIN sales ON buyerId = users.id

表格

Users table:
id     name     type 
1      John     Customer
2      Adam     Customer
3      Robert   Customer

Membership table:
id     userId 
1      1
2      2
3      3


Sales table:
buyerId  total
1        12
1        20
1        5
2        5
2        10
3        5
3        5

期望的输出:

Sales Report:
Name      CustomerId   Total
John      1            37
Adam      2            15
Robert    3            10
SELECT name, membership.userId as customerId, SUM(sales.total) as Total 
FROM users

LEFT OUTER JOIN membership ON membership.userId = users.id
LEFT OUTER JOIN sales ON buyerId = users.id
GROUP BY name, customerId

您需要按用户分组。