首页 > 解决方案 > MYSQL查询每小时/每日消费数据

问题描述

嗨,我需要有关 SQL 查询的帮助。我有一个充满智能电表消耗数据的数据库表。新条目将每分钟添加到 satabase。对于前端,我想显示每日/每小时消耗图表。数据库表如下所示:

Timestamp              AWATT BWATT CWATT
2018-06-01 21:33:56    13.45 4.3   2.78
2018-06-01 21:34:56    14.01 5.0   2.89
...

消费不断增加。所以我想得到每个完整小时和处​​理查询的实际期间的消耗差异,只给数据库一个日期或一个月。

例如。

Timestamp       AWATT BWATT CWATT
00:00 - 01:00   x     y     z
01:00 - 02:00   x1    y1    z1
02:00 - 02:38   x2    y2    z3

查询在 02:38 执行。

我不想在查询完成后进行计算。MYSQL 应该为我完成这项工作。

到目前为止我所拥有的:

select extract(hour from timestamp) as theInterval
     , awatthr 
     , bwatthr 
     , cwatthr 
  from value_table 
 where date_format(timestamp, '%d-%m-%Y') = '01-06-2018' 
 group 
    by extract(hour from timestamp)

结果:

theInterval awatthr bwatthr cwatthr 
0           2955.33 10100.6 13434.8 
1           2963.17 10179.6 13556.5 
2           2994    10251.2 13677.3 
...
22          5702    11704.5 15944.6 
23          6876.93 12078.2 16213.7 

这给了我每整小时的实际值,但不计算两者之间的差异。

你能帮我把缺失的部分添加到这个查询中吗?

标签: mysqlsql

解决方案


一种方法是自联接:

select h.*,
       (h.awatthr - hprev.awatthr) as awatthr_diff,
       (h.bwatthr - hprev.bwatthr) as bwatthr_diff,
       (h.cwatthr - hprev.cwatthr) as cwatthr_diff
from (select extract(hour from timestamp) as theInterval, awatthr as awatthr, bwatthr as bwatthr, cwatthr as cwatthr
      from value_table
      where timestamp >= '2018-06-01' and timestamp < '2018-06-02'
      group by extract(hour from timestamp)
     ) h left join
     (select extract(hour from timestamp) as theInterval, awatthr as awatthr, bwatthr as bwatthr, cwatthr as cwatthr
      from value_table
      where timestamp >= '2018-06-01' and timestamp < '2018-06-02'
      group by extract(hour from timestamp)
     ) hprev
     on h.theInterval = hprev.theInterval + 1;

我应该注意,“正常”的 SQL 方法只是使用lag()窗口函数,现在 MySQL 8 中提供了该函数。

这也使用您编写的查询。它没有点击您在select. 这是一个非常糟糕的习惯,使用了 MySQL 的错误功能。


推荐阅读