我有一个捐赠表,如下。
捐款表
| id| amount | member_id |
|---|--------|-----------|
| 1 | 500 | 01|
| 2 | 1000 | 02|
| 3 | 2000 | 03|
会员表
| id | name | team_id |
|----|--------|-----------|
| 01 | tom | 02|
| 02 | jerry | 01|
| 03 | jane | 01|
队桌
| id | name |
|----|--------|
| 01 | TeamA |
| 02 | TeamB |
如何求和并按组对表进行分组。
| amount | amount |
|--------|-----------|
| TeamA | 3000|
| TeamB | 500|
我尝试使用以下代码,但似乎不起作用。
const totalAmount = await DONATIONS.findAll({
attributes: [
'member_id',
[sequelize.fn('sum', sequelize.col('amount')), 'total_amount'],
],
include:[
{
model: MEMBERS,
include:[
{
model:TEAMS,
group:['name']
},
],
},
],
});
的副本
答案 0 :(得分:1)
您应该能够在mysql端处理它:
SELECT
MAX(t.name) AS TeamName,
SUM(d.amount) AS TotalAmount
FROM team t
INNER JOIN members m ON t.id = m.team_id
INNER JOIN donations d ON m.id = d.member_id
GROUP BY t.id
;