【问题标题】:sum counts across multiple days and group by hour多天的总和计数并按小时分组
【发布时间】:2017-05-03 20:43:41
【问题描述】:

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

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

鉴于此快照中的记录,我如何将它们聚合到多天的hour 存储桶中?

如果我输出查询结果,您可以看到19:0012/1212/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)"));

【问题讨论】:

    标签: javascript node.js postgresql group-by knex.js


    【解决方案1】:

    使用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)
    

    【讨论】:

    • @Growler:错过了ORDER BY 子句中的date_trunc。我修好了。
    • 这很棒。那么date_trunc 有什么用呢? fetches the specific field you asked for 是什么意思? trunc 不也会产生 19th 小时吗?
    • @Growler:您可以在问题的"hour" 字段中看到date_trunc 返回的内容。当您想要比较 2 个时间戳并留有一点余地时,它会很有用:例如,如果您只想比较最新的日期,您可以使用 date_trunc('minute', ts) = date_trunc(…),它会丢弃秒/毫秒精度(将它们设置为 0在检查相等之前的两边)。
    猜你喜欢
    • 2021-06-02
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2020-03-24
    相关资源
    最近更新 更多