根据范围对行进行分组

时间:2018-09-07 14:47:18

标签: sql oracle

如何在oracle中的特定时间范围内对数据进行分组。

我的数据如下:

HHMISS  No_of_Sessions
010101  2
010102  3
010104  5
010107  2
010108  1
010110  6
010111  8
010113  1
010115  6

我的要求是每5秒获取一次会话次数。

HHMISS  No_of_Sessions
010100  10
010105  9
010110  15

1 个答案:

答案 0 :(得分:4)

您的问题令人困惑,因为您发布的结果不符合您描述的要求。

这就是我您要寻找的东西:

SELECT lpad(floor(to_number(hhmiss)/5)*5,6,'0') grp, sum(no_of_session)
from test_data
group by lpad(floor(to_number(hhmiss)/5)*5,6,'0')
order by lpad(floor(to_number(hhmiss)/5)*5,6,'0')

这会将每个输入行分为5秒钟的间隔,然后为您提供每个组中的会话数。

完整示例,其中包含测试数据:

with test_data ( hhmiss, no_of_session ) as
(
SELECT '010101',  2 FROM DUAL UNION ALL
SELECT '010102',  3 FROM DUAL UNION ALL
SELECT '010104',  5 FROM DUAL UNION ALL
SELECT '010107',  2 FROM DUAL UNION ALL
SELECT '010108',  1 FROM DUAL UNION ALL
SELECT '010110',  6 FROM DUAL UNION ALL
SELECT '010111',  8 FROM DUAL UNION ALL
SELECT '010113',  1 FROM DUAL UNION ALL
SELECT '010115',  6 FROM DUAL )
SELECT lpad(floor(to_number(hhmiss)/5)*5,6,'0') grp, sum(no_of_session)
from test_data
group by lpad(floor(to_number(hhmiss)/5)*5,6,'0')
order by lpad(floor(to_number(hhmiss)/5)*5,6,'0')
+--------+--------------------+
|  GRP   | SUM(NO_OF_SESSION) |
+--------+--------------------+
| 010100 |                 10 |
| 010105 |                  3 |
| 010110 |                 15 |
| 010115 |                  6 |
+--------+--------------------+