Node.js 带sequelize的不同计数

Node.js 带sequelize的不同计数,node.js,count,sequelize.js,Node.js,Count,Sequelize.js,我想用sequelize得到一个清晰的计数,比如 'SELECT COUNT(DISTINCT(age)) AS `count` FROM `Persons` AS `Person`' 只要使用原始查询,就可以得到所需的结果。但是,只要我切换到sequelize count函数,查询就会在Postgres中中断: Person.count({distinct:'age'}).then(...); 结果 'SELECT COUNT(DISTINCT(*)) AS `count` FROM `P

我想用sequelize得到一个清晰的计数,比如

'SELECT COUNT(DISTINCT(age)) AS `count` FROM `Persons` AS `Person`'
只要使用原始查询,就可以得到所需的结果。但是,只要我切换到sequelize count函数,查询就会在Postgres中中断:

Person.count({distinct:'age'}).then(...);
结果

'SELECT COUNT(DISTINCT(*)) AS `count` FROM `Persons` AS `Person`'
这会导致语法错误。在不同的帖子中描述的解决方案,例如,不起作用,除非您添加include语句或where子句,而我在这种特殊情况下没有

有人知道这方面的正确解决方案吗?

您必须使用Sequelize才能使其正常工作

Model.aggregate(字段、aggregateFunction、[options])

返回:将聚合结果强制转换为options.dataType,除非 options.plain为false,在这种情况下,完整的数据结果为 返回

例如:

Person.aggregate('age', 'count', { distinct: true })
    .then(function(count) {
      //.. distinct count is here 
    });
正在执行(默认):


您可以这样做:

models.User.findAll({
  attributes: ['user_status',[sequelize.fn('COUNT', sequelize.col('user_status')), 'total']] ,
  group : ['user_status']
});
这将返回类似于:

[
    { user_status : 1 , total : 2 },
    { user_status : 2 , total : 6 },
    { user_status : 3 , total : 9 },
    ...
]

然后,您可以循环查看返回的数据并检查最新版本中的状态,您应该这样做

Person.count({distinct:true, col: 'age'}).then(...);
见:

Person.count({distinct:true, col: 'age'}).then(...);