我需要SQL查询的帮助。我有一个数据库表,里面装满了智能电表的消耗数据。新命令将每分钟添加到数据库中。对于我想要显示每日/每小时消费图表的前端。数据库表如下所示:
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
这给了我每一小时的实际值,但没有计算出两者之间的差异。
你能帮我把这个缺失的部分添加到这个查询中吗?
答案 0 :(得分:1)
一种方法是自我加入:
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的错误。
答案 1 :(得分:0)
SELECT (MAX(awatthr) - MIN(awatthr)) AS awatthr_diff,
(MAX(bwatthr) - MIN(bwatthr)) AS bwatthr_diff,
(MAX(cwatthr) - MIN(cwatthr)) AS cwatthr_diff,
timestamp FROM
`consumption_table` WHERE timestamp > '01-06-2018 00:00:00' AND
timestamp < '01-06-2018 23:59:59' GROUP BY HOUR(timestamp)");
快速回复未来的读者。我认为一个不那么复杂的查询会带来与上面相同的结果。