[英]Get the difference between the min en max value group by month
I've a database with two columns.我有一个包含两列的数据库。
Column 1: named as datum (datetime format)
Column 2: named as Energie (decimal format).
2019-01-01 14:17:07;3419.699951
2019-01-01 14:48:38;3419.800049
2019-01-01 15:12:35;3419.900146
2019-01-01 15:34:26;3420.100098
2019-01-01 15:58:10;3420.300049
2019-01-01 16:21:36;3420.5
2019-01-01 17:20:03;3420.699951
2019-01-01 17:32:11;3420.800049
2019-01-01 17:56:17;3421
2019-01-02 04:40:50;3421.100098
2019-01-02 05:46:28;3421.299805
2019-01-02 05:55:49;3421.400146
2019-01-02 06:41:54;3421.599854
2019-01-02 07:03:16;3421.700195
2019-01-02 07:26:59;3421.899902
2019-01-02 07:39:02;3422
2019-01-02 07:50:57;3422.100098
2019-01-02 08:50:53;3422.300049
2019-01-02 09:12:43;3422.5
2019-01-02 09:24:47;3422.600098
I would like to calculate the difference between the min and max value in column 2 per month and group the results per month.我想计算每月第 2 列中的最小值和最大值之间的差异,并将每月的结果分组。
Till this far I have the following SQL statement what resulted in difference per day.到目前为止,我有以下 SQL 声明导致每天的差异。
select cast(datum as date) AS datum, (max(energie) - min(energie)) as Energie_MWh
from `01` as p
group by
cast(datum as date)
If you are getting data for each day and you want it for month then you can use DATE_FORMAT(cast(datum as date), "%Y%m")
instead of cast(datum as date)
如果您每天都在获取数据并且想要一个月的数据,那么您可以使用DATE_FORMAT(cast(datum as date), "%Y%m")
而不是cast(datum as date)
These lines work for MySQL:这些行适用于 MySQL:
select DATE_FORMAT(datum, "%Y%m") as date_month,
max(energy) as max_engery,
min(energy) as min_energy,
(max(energy) - min(energy)) as diff
from energy_table
group by date_month;
But I wonder if this is a real problem for engergy usage?但我想知道这是否是能源使用的真正问题?
And it will cause a performance problem if the table is large.如果表很大,它会导致性能问题。
MySQL has the very convenient YEAR_MONTH
option for extract()
, so you could use: MySQL 为extract()
提供了非常方便的YEAR_MONTH
选项,因此您可以使用:
select extract(year_month from datum) as yyyymm,
(max(energie) - min(energie)) as Energie_MWh
from `01` as p
group by yyyymm;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.