多天的总计数并按小时分组

咆哮者

我正在尝试使用Knex在多天内按小时对记录进行分组。因此,例如,9AM将是:

{
  hour: 9AM, // for days 12/11, 12/12, 12/13
  count: 10 // 10 Ids total over those days for hour 9AM
}

给定此快照中的记录,如何hour在多天内将它们聚合到存储桶中?

在此处输入图片说明

如果我输出查询结果,您将看到19:00for12/12和的两个单独结果12/13这两天的计数需要归为一hour 19:00组:

ROWS [ anonymous {
    session_ids: [ 3200 ],
    hour: 2016-12-12T14:00:00.000Z,
    count: '1' },
  anonymous {
    session_ids: [ 3201 ],
    hour: 2016-12-12T15:00:00.000Z,
    count: '1' },
  anonymous {
    session_ids: [ 3203, 3202 ],
    hour: 2016-12-12T19:00:00.000Z,
    count: '2' },
  anonymous {
    session_ids: [ 3204, 3205 ],
    hour: 2016-12-13T19:00:00.000Z, // This count should be aggregated into the `19:00` grouping above
    count: '2' } ]

我当前的查询:

var qry = db.knex
  .select(db.knex.raw("array_agg(t2.id) as session_ids, date_trunc('hour', t2.start_timestamp) as hour"))
  .count('*')
  .from('sessions as t2')
  .groupByRaw("date_trunc('hour', t2.start_timestamp)")
  .orderBy(db.knex.raw("date_trunc('hour', t2.start_timestamp)"));
马思

使用EXTRACT,而不是date_trunc

var qry = db.knex
  .select(db.knex.raw("array_agg(t2.id) as session_ids, extract('hour' from t2.start_timestamp) as hour"))
  .count('*')
  .from('sessions as t2')
  .groupByRaw("extract('hour' from t2.start_timestamp)")
  .orderBy(db.knex.raw("extract('hour' from t2.start_timestamp)"));

date_trunc将时间戳截断为指定的精度(这意味着GROUP BY将不起作用,因为两个具有相同“小时”字段的时间戳的日期可能仍然不同):

SELECT date_trunc('hour', NOW());
┌────────────────────────┐
│       date_trunc       │
├────────────────────────┤
│ 2016-12-18 19:00:00+01 │
└────────────────────────┘
(1 row)

同时EXTRACT获取您要求的特定字段:

SELECT extract('hour' from NOW());
┌───────────┐
│ date_part │
├───────────┤
│        19 │
└───────────┘
(1 row)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章