How does group by works in sequelize?

前端 未结 7 482
不知归路
不知归路 2020-12-16 09:18

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

    SELEC         


        
相关标签:
7条回答
  • 2020-12-16 09:40

    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) => { })
    
    0 讨论(0)
  • 2020-12-16 09:48

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

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

    i use sequelize@2.0.0-dev9

    0 讨论(0)
  • 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.
    
    0 讨论(0)
  • 2020-12-16 09:50

    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'],
    })
    
    0 讨论(0)
  • 2020-12-16 09:54

    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) { });
    
    0 讨论(0)
  • 2020-12-16 09:59

    Try this -

    Table.count(
    {
       attributes: ['column'], 
       group: 'column',
    } 
    
    0 讨论(0)
提交回复
热议问题