How does group by works in sequelize?

大兔子大兔子 提交于 2019-12-21 06:46:29

问题


I am looking for group by queries through Sequelize and cannot seem to find any documentation.

SELECT column, count(column)  
FROM table 
GROUP BY column

回答1:


issue: https://github.com/sequelize/sequelize/issues/348

User.findAll({
 group: ['field']
})

i use sequelize@2.0.0-dev9




回答2:


I think you looking for something like this:

 Table.findAll({
   attributes: ['column1', 
     sequelize.fn('count', sequelize.col('column2'))], 
   group: ["Table.column1"]
 }).success(function (result) { });

Update: Newer versions of Sequelize uses .then instead of .success.

 Table.findAll({
   attributes: ['column1', 
     sequelize.fn('count', sequelize.col('column2'))], 
   group: ["Table.column1"]
 }).then(function (result) { });



回答3:


Group by with count sequelize ORM

'field' - you can rename this string, it's your field(column) in database

'count' - reserved string need for get count in sequelize

'cnt' - you can rename this string, it's your output count

Sequelize version 3.25.0

User.findAll({
      attributes: ['field', [sequelize.fn('count', sequelize.col('field')), 'cnt']],
      group: ['field'],
})



回答4:


Try this -

Table.count(
{
   attributes: ['column'], 
   group: 'column',
} 



回答5:


Example: how to add an convenient alias to the grouped function column.

I did this as a separate response mostly because it wouldn't format well in a comment... otherwise I would have just added it to Sampat's answer.

function getSumsBySomeId() {
  const criteria = {
    attributes: ['some_id', [sequelize.fn('sum', sequelize.col('some_count')), 'some_count_sum']],
    group: ['some_id'],
    raw: true
  };
  return Table.getAll(criteria);
}

YIELDS:

{ some_id: 42, some_count_sum: 100 },
{ some_id: 43, some_count_sum: 150 }
...
etc.



回答6:


Your code should look something like these using ES6 standard.

Table.findAll({ attributes: ['column1', sequelize.fn('count', sequelize.col('column2'))],   group: ["Table.column1"]  }).then( (result) => { })



回答7:


**Try this*

Table.findAll({
     group: ['column']
})


来源:https://stackoverflow.com/questions/22627258/how-does-group-by-works-in-sequelize

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