查询每天的价值变化?

时间:2013-12-07 16:00:17

标签: mysql graphing

我在MySQL数据库中有一些历史数据,我正在制作它的图表。目前,我的图表看起来像这样:

enter image description here

然而,我希望随着时间的推移在值中获得更改 - 即显示自上次测量以来的更改。这样的事情(显然数据不正确):

enter image description here

如何编写一个MySQL查询,与前一行相比得到一个值的增量?

这是我当前的查询,在juergen d的帮助下:

SELECT `timestamp`, total_users, total_users - @prev AS col1, @prev := total_users, FROM stats, (select @prev := 0) p GROUP BY DAY(`timestamp`), floor(HOUR(`timestamp`)/2)

1 个答案:

答案 0 :(得分:4)

一般

使用包含最后记录值的变量来计算delta

select some_column, 
       some_column - @prev as delta, 
       @prev := some_column
from your_table, (select @prev := 0) p

SQLFiddle demo

实际查询

SELECT DAY(`timestamp`) as day_ts, 
       floor(HOUR(`timestamp`)/2) as hour_ts
       sum(total_users)
       sum(total_users) - @prev AS col1, 
       @prev := sum(total_users)
FROM stats, (select @prev := 0) p 
GROUP BY day_ts, hour_ts