【问题标题】:以 10 分钟为时间间隔的 DB2 SQL 组行计数
【发布时间】:2022-01-22 09:09:01
【问题描述】:

我在 DB2 中有一个表,其中包含如下数据:

completed_timestamp details
2021-12-19-15.38.10 abcd
2021-12-19-15.39.10 efgh
2021-12-19-15.48.10 ijkl
2021-12-19-15.49.10 mnop
2021-12-19-15.54.10 qrst

我希望能够每 10 分钟计算一次表中的行数,例如

Time count
2021-12-19-15.40 2
2021-12-19-15.50 2
2021-12-19-16.00 1

completed_timestamp = 时间戳,详细信息 = varchar

我已经在其他 SQL 语言中看到过这样做,但到目前为止还没有弄清楚如何使用 DB2 来做到这一点。我该怎么做?

【问题讨论】:

  • 我将通过递归 CTE 动态地“10 分钟开始-结束”“表”,然后将其与主表 LEFT JOIN。

标签: sql group-by db2


【解决方案1】:

您可以从时间戳中获取分钟,将其除以十,得到下一个整数,乘以十并将其作为分钟添加到小时:

WITH TABLE1 (completed_timestamp, details) AS (
 VALUES 
 (timestamp '2021-12-19-15.38.10', 'abcd'),
 (timestamp '2021-12-19-15.39.10', 'efgh'),
 (timestamp '2021-12-19-15.48.10', 'ijkl'),
 (timestamp '2021-12-19-15.49.10', 'mnop'),
 (timestamp '2021-12-19-15.54.10', 'qrst')
),
trunc_timestamps (time, details) AS (
  SELECT trunc(completed_timestamp, 'HH24') + (ceiling(minute(completed_timestamp) / 10.0) * 10) MINUTES, details FROM table1
)
SELECT trunc_timestamps.time, count(*) FROM trunc_timestamps GROUP BY trunc_timestamps.time

【讨论】:

    猜你喜欢
    • 2016-04-15
    • 2015-02-01
    • 2014-01-26
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多