【问题标题】:Multiple count query in sequelize ORMsequelize ORM中的多个计数查询
【发布时间】:2015-08-21 07:09:00
【问题描述】:

我想创建一个查询,该查询能够在 sequelize.js 中一次计算每月每一天的记录数 不像:

Record.count({ where: { createdAt: { $like: '2015-04-14%' } } }).then(function(c) {
  console.log("2015-04-14 have been created" + c + "records");
});

Record.count({ where: { createdAt: { $like: '2015-04-15%' } } }).then(function(c) {
  console.log("2015-04-15 have been created" + c + "records");
});


Record.count({ where: { createdAt: { $like: '2015-04-16%' } } }).then(function(c) {
  console.log("2015-04-16 have been created" + c + "records");
});

....
....

我想进行一次返回行数的查询,而不是在 30 个查询中向数据库询问此数据。可以通过交易实现吗?

我会将它用于图表目的,因此最好的输出如下:

[500, 300, 400, 550....]

感谢您的帮助!

【问题讨论】:

    标签: node.js postgresql charts sequelize.js c3.js


    【解决方案1】:

    对于这种类型的查询,您可以使用带有分组的 postgresql date_trunc 函数:

    db.record.findAll({
      attributes: [
        [
          db.sequelize.fn('date_trunc', 
            'day', 
            db.sequelize.col('createdAt')
          ), 
          'dateTrunc'
        ],
        [
          db.sequelize.fn('count', 
            db.sequelize.col('id')
          ), 
          'count'
        ]
      ],
      group: '"dateTrunc"'
    }).then(function(rows) {
      console.log(rows);
    });
    

    【讨论】:

    • 非常感谢,我已经用原始查询创建了它。基本上你的解决方案是一样的。
    • 你真的是DJ吗?我在这行中有价格列。你知道在这种情况下我如何对特定日期的所有记录求和所有这些价格吗?
    • 使用sum 函数代替count。请参阅此属性定义:[ db.sequelize.fn('sum', db.sequelize.col('price') ), 'priceSum' ]
    【解决方案2】:

    我的 PostgreSQL 原始查询解决方案:

    db.sequelize
      .query("SELECT count(*), date_trunc('month', \"createdAt\") AS date FROM tables WHERE active = true AND \"createdAt\" BETWEEN '"+moment().startOf('year').format()+"' AND '"+moment().format()+"' GROUP BY date")
      .then(function(results){
         res.json(results[0]);
    });
    

    我希望它对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2022-12-29
      • 2018-11-06
      • 1970-01-01
      • 2022-10-14
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多