Eed*_*doh 5 javascript grouping date node.js sequelize.js
我正在尝试使用 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'
})
}
Run Code Online (Sandbox Code Playgroud)
然而,我得到的输出并不是每天的小计。我实际上从表中获取了每条记录,时间部分设置为 00:00:000Z
为了获得每天的小计,我应该更改什么?
我想我自己找到了解决方案......
上面引用的方法生成以下 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;
Run Code Online (Sandbox Code Playgroud)
这里的问题是,虽然我选择“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'
})
}
Run Code Online (Sandbox Code Playgroud)
请注意,我还必须使用
[[Sequelize.literal('"createdOn"'), 'ASC']],
Run Code Online (Sandbox Code Playgroud)
in order 子句,而不是仅使用别名。这是因为 Sequelize 不断将 order 子句中别名列的大小写更改为“createdon”...
希望这对某人有帮助。
| 归档时间: |
|
| 查看次数: |
4408 次 |
| 最近记录: |