mySql 中的小时明智数据

Hour Wise data in mySql

我有 table 具有以下字段

Createdon(datetime)
Amount(double)

我需要找到给定日期接下来 24 小时内的金额总和。如果没有结果,则总和应为零。 例如

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

你能帮我创建一个查询来找到所需的解决方案吗

查询的关键是能够获取任何 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')

最后,您需要以某种方式获得 table 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/

中以更一般的形式编写的