【问题标题】:How to group by createdAt column's date part?如何按 createdAt 列的日期部分分组?
【发布时间】:2019-04-02 15:21:04
【问题描述】:

我正在尝试使用 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

为了获得每天的小计,我应该改变什么?

【问题讨论】:

  • 你试过用[Sequelize.fn('date_trunc', 'day', Sequelize.col('createdAt')), 'createdAt']分组
  • 是的,没有效果,很遗憾

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


【解决方案1】:

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

上面引用的方法产生以下 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']],

in order 子句,而不是只使用别名。那是因为 Sequelize 不断将 order 子句中 alias 列的大小写更改为“createdon”...

希望这对某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 2014-05-01
    相关资源
    最近更新 更多