I'm trying to get some subtotals using Sequelize, and this is how my query looks like.
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'
})
}
However, what I get as an output are not subtotals on per-day basis. I actually get each and every record from the table, with time part set to 00:00:000Z
What should I change in order to get subtotals for each day?
I'm trying to get some subtotals using Sequelize, and this is how my query looks like.
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'
})
}
However, what I get as an output are not subtotals on per-day basis. I actually get each and every record from the table, with time part set to 00:00:000Z
What should I change in order to get subtotals for each day?
Share Improve this question asked Oct 29, 2018 at 16:23 EedohEedoh 6,3289 gold badges42 silver badges63 bronze badges 2-
1
Have you tried grouping with
[Sequelize.fn('date_trunc', 'day', Sequelize.col('createdAt')), 'createdAt']
– Sushant Commented Oct 30, 2018 at 12:04 - Yes, with no effect, unfortunatelly – Eedoh Commented Oct 30, 2018 at 12:27
1 Answer
Reset to default 5I think I found the solution myself...
The above quoted method produces the following SQL query
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;
The problem here is that although I'm selecting "createdAt" as an alias for truncated value from createdAt column, Sequelize is still referencing createdAt column in the table, and not the alias.
I went around this issue by renaming the alias to "createdOn", like this
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'
})
}
Notice that I had to also use
[[Sequelize.literal('"createdOn"'), 'ASC']],
in order clause, instead of just using alias name. That's because Sequelize kept changing capitalization of the alias column in order clause to "createdon"...
Hope this helps someone.