How to get a distinct count with sequelize?

前端 未结 4 2044
长发绾君心
长发绾君心 2021-02-12 02:27

I am trying to get a distinct count of a particular column using sequelize. My initial attempt is using the \'count\' method of my model, however it doesn\'t look like this is

4条回答
  •  渐次进展
    2021-02-12 03:04

    The Sequelize documentation on count links to a count method that doesn't let you specify which column to get the count of distinct values:

    Model.prototype.count = function(options) {
      options = Utils._.clone(options || {});
      conformOptions(options, this);
      Model.$injectScope(this.$scope, options);
      var col = '*';
      if (options.include) {
        col = this.name + '.' + this.primaryKeyField;
        expandIncludeAll.call(this, options);
        validateIncludedElements.call(this, options);
      }
      Utils.mapOptionFieldNames(options, this);
      options.plain = options.group ? false : true;
      options.dataType = new DataTypes.INTEGER();
      options.includeIgnoreAttributes = false;
      options.limit = null;
      options.offset = null;
      options.order = null;
      return this.aggregate(col, 'count', options);
    };
    

    Basically SELECT COUNT(DISTINCT(*)) or SELECT COUNT(DISTINCT(primaryKey)) if you've got a primary key defined.

    To do the Sequelize equivalent of SELECT category, COUNT(DISTINCT(product)) as 'countOfProducts' GROUP BY category, you'd do:

    model.findAll({
      attributes: [
        'category',
        [Sequelize.literal('COUNT(DISTINCT(product))'), 'countOfProducts']
      ],
      group: 'category'
    })
    

提交回复
热议问题