我正在使用带有NodeJS的postgres和knex在给定日期范围内将会话标识按小时聚合。我的start_timestamp格式为2016-12-12 14:53:17.243-05
。我想按小时对所有记录进行分组,例如:knex SQL - 列必须出现在GROUP BY子句中或用于聚合函数中
- 小时
14:00:00-15:00:00
在该小时内将有n条记录。 - 小时
15:00:00-16:00:00
在该小时内将有n条记录。 - 等...
鉴于查询
db.knex.count('t1.id as session_ids')
.from('sessions as t1')
.where(db.knex.raw('t1.start_timestamp'), '>=', startDate)
.andWhere(db.knex.raw('t1.start_timestamp'), '<=', endDate)
.groupByRaw("date_trunc('hour', t1.start_timestamp)");
我的开始日期和结束日期决定的范围1日。所以根据每天的小时分组不应该有重复/模糊的时间。
我成功地可以按小时来获得每个记录的计数:
[ anonymous { session_ids: '6' },
anonymous { session_ids: '1' },
anonymous { session_ids: '1' },
anonymous { session_ids: '3' },
...
但我需要显示自己的实际时间,因为这样的:
{
hour: 10
session_ids: 5 //5 session IDs
}
下面count
添加.select('t1.start_timestamp')
,如图所示in this example,出现以下错误:
Unhandled rejection error: column "t1.start_timestamp" must appear in the GROUP BY clause or be used in an aggregate function
由于t1.start_timestamp
出现在GROUP BY阶段,所以此错误对我无意义。
此外,我已经检查出PostgreSQL -must appear in the GROUP BY clause or be used in an aggregate function寻求帮助。我的记录中没有歧义,因此数据库应该知道要选择哪些记录。