每日汇总到每月数据并计算delta mysql

时间:2015-09-01 06:39:48

标签: mysql

大家好我所有的mysql结果都是这样的:

+---------------------+------+
|      timestamp      | data |  
+---------------------+------+
| 2015-06-01 04:25:18 |   10 |  
| 2015-06-15 04:25:18 |   20 |  
| 2015-06-30 04:25:18 |   30 |  
| 2015-07-01 04:25:18 |   50 |  
| 2015-07-15 04:25:18 |   60 |  
| 2015-07-30 04:25:18 |   70 |  
| 2015-08-01 04:25:18 |   80 |  
| 2015-08-15 04:25:18 |   90 |  
| 2015-08-30 04:25:18 |  100 |  
+---------------------+------+

我可以使用查询来计算delta,所以就像这样:

+---------------------+------+------+
|      timestamp      | data | delta |
+---------------------+------+------+
| 2015-06-01 04:25:18 |   10 |    0 |
| 2015-06-15 04:25:18 |   20 |   10 |
| 2015-06-30 04:25:18 |   30 |   10 |
| 2015-07-01 04:25:18 |   50 |   20 |
| 2015-07-15 04:25:18 |   60 |   10 |
| 2015-07-30 04:25:18 |   70 |   10 |
| 2015-08-01 04:25:18 |   80 |   10 |
| 2015-08-15 04:25:18 |   90 |   10 |
| 2015-08-30 04:25:18 |  100 |   10 |
+---------------------+------+------+

我所追求的是按月分组delta列:

+-------+-------------+
| month | consumption |
+-------+-------------+
| 6/15  |          20 |
| 7/15  |          40 |
| 8/15  |          30 |
+-------+-------------+

我以为我必须尝试GROUP BY MONTH(时间戳),但它不会聚合增量。

有什么想法吗?

修改

澄清delta是一个计算列,这里是一个修改过的查询,向您展示我的意思:

 SELECT 
node_time,
   node_read - @prev AS delta,
  @prev := waveflow_data.node_read
FROM
  meter_data
INNER JOIN waveflow_data ON meter_data.node_address = waveflow_data.node_address 
CROSS JOIN (SELECT @prev := (SELECT node_read FROM waveflow_data ORDER BY `node_time` DESC LIMIT 1)) variable_initialization_query_alias
WHERE
   meter_data.node_address = '10164E998976' 
ORDER BY waveflow_data.`node_time` DESC

3 个答案:

答案 0 :(得分:0)

您只需要sum(delta)如下所示:

select time_stamp,sum(delta) as Consumption from test 
        group by month(time_stamp);

检查SQL FIDDLE DEMO

答案 1 :(得分:0)

如果您希望得到初始给定数据集的最终结果,那么您可以

select
date_format(timestamp,'%m/%y') as month,
sum(delta) as delta 
from
(
  select
  timestamp,
  data,
  @diff:= if(@prev=0,0,(data - @prev)) as delta,
  @prev:= data
  from table_name,(select @prev:=0)x 
  order by timestamp
)x
group by month;

<强> DEMO

答案 2 :(得分:0)

假设您有Templates

之类的查询

将其更新为Select timestamp,data,delta from mytable groupby timestamp

时间戳现在将采用您想要的格式,并且将根据该时间自动进行分组。