重复计数ORM中的多个计数查询
我想创build查询,它可以在sequelize.js一次在一个月的每一天的logging数不是像:
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....]
谢谢你的帮助!
对于这种types的查询,可以使用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); });
我的解决scheme与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]); });
我希望这有助于某人。