我有这样的数据
+-----------------------+---------+
| DateTime | Value |
+-----------------------+---------+
| 2015-08-18 19:36:42 | 22 |
| 2015-08-18 20:48:49 | 20 |
| 2015-08-18 21:48:49 | 19 |
| 2015-08-18 22:48:49 | 23 |
| 2015-08-18 23:48:49 | 20 |
| 2015-08-19 00:48:49 | 23 |
| 2015-08-19 01:48:49 | 21 |
| 2015-08-19 02:48:49 | 15 |
... ...
| 2015-08-19 22:30:16 | 21 |
| 2015-08-19 23:30:16 | 22 |
| 2015-08-20 00:30:16 | 25 |
| 2015-08-20 01:30:16 | 26 |
... ...
| 2015-08-20 22:30:16 | 19 |
| 2015-08-20 23:30:16 | 20 |
| 2015-08-21 00:30:16 | 21 |
| 2015-08-21 01:30:16 | 21 |
... ...
我想选择从当前日期06:00:00到下一个日期06:00:00结束的夜晚的平均夜晚。 喜欢2015-08-18的夜晚作为'2015-08-18' 我希望最终结果如下所示:
+---------------+---------+
| DateTime | AvgValue|
+---------------+---------+
| 2015-08-18 | 22 |
| 2015-08-19 | 20 |
| 2015-08-20 | 19 |
| 2015-08-21 | 23 |
| 2015-08-22 | 20 |
... ..
我已经浏览了很多网站,预订并通过大多数教程,但我无法想办法如何编写此查询来执行此操作。
任何人都可以帮我查询以获得上述结果。
答案 0 :(得分:0)
我会建议这样的查询,虽然它可能很慢:
select date(`DateTime` - interval 6 hour), avg(`Value`) as AvgValue
from tblName
group by date(`DateTime` - interval 6 hour)
order by 1 asc
但我强烈建议添加一个仅存储记录所属的夜晚(没有时间)的附加列,并为该列添加索引,以便更快地处理查询。
答案 1 :(得分:0)
select if(hour(DateTime) >= 18,
date(date_add(Datetime, interval 1 day)), date(Datetime)) DateAct,
avg(`Value`) as AvgValue
from yourTable
group by DateAct
order by 1;