Node.js knex SQL-列必须出现在GROUP BY子句中,或在聚合函数中使用
我使用postgres和knex与NodeJS在给定日期范围内按小时聚合会话ID。我的开始时间戳的格式为Node.js knex SQL-列必须出现在GROUP BY子句中,或在聚合函数中使用,node.js,postgresql,knex.js,Node.js,Postgresql,Knex.js,我使用postgres和knex与NodeJS在给定日期范围内按小时聚合会话ID。我的开始时间戳的格式为2016-12-12 14:53:17.243-05。我希望按小时对所有记录进行分组,以便: 小时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
2016-12-12 14:53:17.243-05
。我希望按小时对所有记录进行分组,以便:
- 小时
将在该小时内有n条记录14:00:00-15:00:00
- 小时
将在该小时内有n条记录15:00:00-16:00:00
- 等等
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)");
但我需要显示它们的实际时间,如下所示:
{
hour: 10
session_ids: 5 //5 session IDs
}
在下面添加。选择('t1.start\u timestamp')
,如图所示,我得到以下错误:
未处理的拒绝错误:列“t1.start\u timestamp”必须出现在
GROUP BY子句或GROUP BY子句不能用于聚合函数
这个错误对我来说没有意义,因为t1.start\u timestamp
在GROUP BY stage中出现
而且,我已经去求助了。我的记录没有歧义,因此DB应该知道要选择哪些记录。我不熟悉knex,但以下查询不起作用(它给出了与您注意到的相同的错误消息): 但是,以下查询不起作用:
SELECT date_trunc('hour', t1.start_timestamp), count(t1.id) AS session_ids
FROM sessions AS t1
GROUP BY date_trunc('hour', t1.start_timestamp);
您可以尝试更改。请相应地选择吗
SELECT t1.start_timestamp, count(t1.id) AS session_ids
FROM sessions AS t1
GROUP BY date_trunc('hour', t1.start_timestamp);
SELECT date_trunc('hour', t1.start_timestamp), count(t1.id) AS session_ids
FROM sessions AS t1
GROUP BY date_trunc('hour', t1.start_timestamp);