Finding sum and grouping in sequelize

∥☆過路亽.° 提交于 2019-12-10 15:13:45

问题


I have a donations table as follows.

Donations Table

| id| amount | member_id |
|---|--------|-----------|
| 0 |   500  |         01|
| 1 |  1000  |         02|
| 2 |  2000  |         01|

How to find sum and group the table by member id as follows.

| amount | member_id |
|--------|-----------|
|  2500  |         01|
|  1000  |         02|

I tried to use the following code but it doesnt seem to work.

const salesValue = await DONATIONS.sum('amount', {
    group: 'member_id'
});

回答1:


const totalAmount = await DONATIONS.findAll({
        attributes: [
          'member_id',
          [sequelize.fn('sum', sequelize.col('amount')), 'total_amount'],
        ],
        group: ['member_id'],
      });



回答2:


This should be your MySQL query:

select sum(amount),member_id from myTable group by member_id;

Now parse the output in nodejs.

Thanks



来源:https://stackoverflow.com/questions/56538035/finding-sum-and-grouping-in-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!