如何按createdAt列的日期部分分组?

时间:2018-10-29 16:23:35

标签: javascript node.js date sequelize.js grouping

我正在尝试使用Sequelize获取一些小计,这就是查询的样子。

const getAllCustomerEarnings = async (customerAccountId) => {
  return await customerEarnings.findAll({
    attributes: [
      [Sequelize.fn('SUM', Sequelize.col('amount')), 'amount'],
      [Sequelize.fn('date_trunc', 'day', Sequelize.col('createdAt')), 'createdAt'],
    ],
    where: { 
      [Op.and]: [
        {customerAccountId: customerAccountId},
      ] 
    },
    order: [['createdAt', 'ASC']],
    group: 'createdAt'
  })
}

但是,我得到的输出不是每天的小计。我实际上从表中获取每条记录,时间部分设置为00:00:000Z

我应该改变什么以获得每天的小计?

1 个答案:

答案 0 :(得分:0)

我想我自己找到了解决方法...

上面引用的方法产生以下SQL查询

SELECT SUM("amount") AS "amount", date_trunc('day', "createdAt") AS "createdAt"
FROM "CustomerEarnings" AS "CustomerEarning"
WHERE ("CustomerEarning"."customerAccountId" = 5)
GROUP BY "createdAt"
ORDER BY "CustomerEarning"."createdAt" ASC;

这里的问题是,尽管我从createdAt列中选择“ createdAt”作为截断值的别名,但Sequelize仍在引用表中的createdAt列,而不是别名。

我通过将别名重命名为“ createdOn”来解决了这个问题,就像这样

const getAllCustomerEarnings = async (customerAccountId) => {
  return await customerEarnings.findAll({
    attributes: [
      [Sequelize.fn('SUM', Sequelize.col('amount')), 'amount'],
      [Sequelize.fn('date_trunc', 'day', Sequelize.col('createdAt')), 'createdOn'],
    ],
    where: { 
      [Op.and]: [
        {customerAccountId: customerAccountId},
      ] 
    },
    order: [[Sequelize.literal('"createdOn"'), 'ASC']],
    group: 'createdOn'
  })
}

请注意,我也必须使用

[[Sequelize.literal('"createdOn"'), 'ASC']],

order子句,而不仅仅是使用别名。这是因为Sequelize一直将order子句中别名列的大小写更改为“ createdon” ...

希望这对某人有帮助。