I am using Postgres with NodeJS and Knex. I have a number of records with created_at format 2016-12-12 14:53:17.243-05
. I want to group all records by the hour such that:
- Hour
14:00:00-15:00:00
would have n records within that hour. - Hour
15:00:00-16:00:00
would have n records within that hour. - etc...
I was going to do this by simply querying for the records I want, then using momentJS
to group them by hour, but I think this should be handled on the query. I'm just not sure what the syntax looks like.
Here's my starting query:
getChatVolume: function(startDate, endDate) {
var chats = db.knex
.select(['sessions.id', db.knex.raw('sessions.start_timestamp::date as date')])
.from('sessions')
.where(db.knex.raw('sessions.start_timestamp'), '>=', startDate)
.andWhere(db.knex.raw('sessions.start_timestamp'), '<=', endDate)
.groupByRaw("date_trunc('hour', sessions.start_timestamp)")
return chats;
},
This explains how you can do it for MySQL, Oracle, and SQL Server, but not Knex.