sqlite:按时间戳分组的结果组和5分钟的间隔

时间:2017-08-17 06:31:20

标签: python-2.7 sqlite group-by timestamp

我正在尝试拆分最后一小时数据,最后六小时,最后六天和六个月的数据。我已经看到大多数答案适用于MySQL,如何在sqlite中实现这一点? 我试过这个sqlite查询:

SELECT timestamp,usage FROM network_band WHERE timestamp <= '2017-08-17 10:57:26' and timestamp >= '2017-08-17 09:57:26'  and mac='68:c4:4d:8b:65:dd' GROUP BY strftime('%H:%M:%S 00:00:00', timestamp, '+5 minutes')

得到的结果是:

"2017-08-17 10:30:26"   "0.00208962886"
"2017-08-17 10:30:32"   "0.02299923714"
"2017-08-17 10:30:35"   "0.18050153"
"2017-08-17 10:30:38"   "0.761394722"
"2017-08-17 10:30:47"   "9.905705062"
"2017-08-17 10:30:51"   "6.078996"
"2017-08-17 10:30:57"   "11.204719152"
"2017-08-17 10:31:00"   "5.284454384"
"2017-08-17 10:31:06"   "6.86252996"
"2017-08-17 10:31:09"   "3.79881057599999"
"2017-08-17 10:31:12"   "0.798022895999992"
"2017-08-17 10:32:52"   "0.00697107399999197"
"2017-08-17 10:32:55"   "0.0328375519999895"
"2017-08-17 10:32:58"   "0.0226850799999951"
"2017-08-17 10:33:01"   "0.0220522059999979"
"2017-08-17 10:34:08"   "0.0676957600000065"
"2017-08-17 10:34:14"   "0.00304612000000759"
"2017-08-17 10:34:45"   "0.0634264620000096"
"2017-08-17 10:34:51"   "0.038900465999987"
"2017-08-17 10:34:57"   "0.00548396199999957"
"2017-08-17 10:35:21"   "0.0180780599999935"
"2017-08-17 10:35:28"   "0.0658217339999965"
"2017-08-17 10:35:38"   "5.418789222"
"2017-08-17 10:36:38"   "0.000912889999995059"
"2017-08-17 10:36:59"   "0.00126196399999401"
"2017-08-17 10:37:02"   "8.46684473799999"
"2017-08-17 10:37:05"   "4.540849192"
"2017-08-17 10:37:08"   "1.82630219199999"
"2017-08-17 10:37:11"   "0.689901717999987"
"2017-08-17 10:37:20"   "0.000524084000005587"
"2017-08-17 10:37:33"   "0.0693058519999994"
"2017-08-17 10:37:39"   "0.151251209999998"
"2017-08-17 10:37:45"   "3.526737192"
"2017-08-17 10:38:00"   "20.165658744"
"2017-08-17 10:38:06"   "0.00512826599999983"
"2017-08-17 10:38:55"   "0.124861593999995"
"2017-08-17 10:39:01"   "0.258720593999996"
"2017-08-17 10:39:08"   "0.362066363999986"
"2017-08-17 10:39:14"   "0.0221023439999897"
"2017-08-17 10:39:51"   "0.194911001999998"
"2017-08-17 10:40:00"   "0.128526397999991"
"2017-08-17 10:40:12"   "0.0315613979999938"
"2017-08-17 10:40:15"   "0.0247038439999869"
"2017-08-17 10:40:18"   "0.091926603999994"

期望的输出:

类似的东西:

**"2017-08-17 10:30:26"   "0.00208962886"
"2017-08-17 10:35:28"   "sum(10:30 to 10:35)"
"2017-08-17 10:40:18"   "sum(10:35 to 10:40)"**

1 个答案:

答案 0 :(得分:0)

GROUP BY strftime('%H:%M:%S 00:00:00', timestamp, '+5 minutes')

这会将时间戳移动到未来五分钟,但不同的时间戳仍然是不同的时间戳。 但是分组要求组中的所有行在GROUP BY子句中以相同的值结束。

在SQLite中,您可以通过将时间戳转换为秒数(strftime('%s', ...)),除以间隔中的秒数,然后舍入(舍入与整数除法隐含)来实现:

...
GROUP BY strftime('%s', timestamp) / 6 * 60 * 60   -- six hours