mySql中的Hour Wise数据

时间:2015-04-21 12:08:35

标签: mysql datetime group-by time-series aggregate-functions

我的表格包含以下字段

Createdon(datetime)
Amount(double)

我需要查找给定日期的下一个24小时的金额总和。如果没有结果则总和应为零。 例如

duration  sum
0000-0001 25.43
0001-0002 36.85
0002-0003 0
.
.
.
.
0022-0023 38.56

是否可以帮我创建查询以找到所需的解决方案

1 个答案:

答案 0 :(得分:1)

查询的关键是能够获取任何datetime值并将其截断到最接近的前一小时。你可以用这个表达式来做到这一点:

 DATE_FORMAT(Createdon, '%Y-%m-%d %H:00')

例如,2015-04-21 14:22:05,这会返回2015-04-21 14:00:00

然后在GROUP BY中使用它

SELECT DATE_FORMAT(Createdon, '%Y-%m-%d %H:00') Createdhour,
       SUM(Amount) sum
  FROM theTable
 GROUP BY DATE_FORMAT(Createdon, '%Y-%m-%d %H:00')
 ORDER BY DATE_FORMAT(Createdon, '%Y-%m-%d %H:00')

最后,我想你想要一天的结果。您需要添加WHERE子句才能获得该子句。这里显示的结果将取得昨天的结果 - 也就是说,所有结果都来自[昨天午夜 - 今天午夜]。

SELECT DATE_FORMAT(Createdon, '%Y-%m-%d %H:00') Createdhour,
       SUM(Amount) sum
  FROM theTable
 WHERE CreatedOn >= DATE(NOW()) - INTERVAL 1 DAY
   AND CreatedOn <  DATE(NOW())
 GROUP BY DATE_FORMAT(Createdon, '%Y-%m-%d %H:00')
 ORDER BY DATE_FORMAT(Createdon, '%Y-%m-%d %H:00')

http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

更详细地解释了这一点

要包含一天中的所有小时数,您需要一个独立的DATETIME项独立来源。

这是一个会做这样事情的查询。

      SELECT mintime + INTERVAL seq.seq HOUR AS CreatedHour
        FROM (
              SELECT DATE(NOW()) - INTERVAL 1 DAY AS mintime,
                     DATE(NOW()) AS maxtime
             ) AS minmax
        JOIN seq_0_to_23 AS seq 
              ON seq.seq < TIMESTAMPDIFF(HOUR,mintime,maxtime)

然后,您需要使用LEFT JOIN来获取数据。

SELECT a.Createdhour,
       SUM(Amount) sum
  FROM (
      SELECT mintime + INTERVAL seq.seq HOUR AS CreatedHour
        FROM (
              SELECT DATE(NOW()) - INTERVAL 1 DAY AS mintime,
                     DATE(NOW()) AS maxtime
             ) AS minmax
        JOIN seq_0_to_23 AS seq 
              ON seq.seq < TIMESTAMPDIFF(HOUR,mintime,maxtime)
       ) a
  LEFT JOIN theTable t 
          ON a.CreatedHour  = DATE_FORMAT(t.Createdon, '%Y-%m-%d %H:00')
 GROUP BY DATE_FORMAT(t.Createdon, '%Y-%m-%d %H:00')
 ORDER BY DATE_FORMAT(t.Createdon, '%Y-%m-%d %H:00')

最后,您需要以某种方式获取该表seq_0_to_23。如果你正在运行MariaDB,它就是内置的。如果不是......

CREATE TABLE seq_0_to_23 AS
 SELECT 0 AS seq 
  UNION ALL SELECT  1 UNION ALL SELECT  2 UNION ALL SELECT  3
  UNION ALL SELECT  4 UNION ALL SELECT  5 UNION ALL SELECT  6
  UNION ALL SELECT  7 UNION ALL SELECT  8 UNION ALL SELECT  9
  UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
  UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15
  UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18
  UNION ALL SELECT 19 UNION ALL SELECT 20 UNION ALL SELECT 21
  UNION ALL SELECT 22 UNION ALL SELECT 23

这是以http://www.plumislandmedia.net/mysql/filling-missing-data-sequences-cardinal-integers/

的更一般形式编写的