MYSQL - 确定一行中的先前值

时间:2014-03-29 01:46:47

标签: mysql

我希望在将时间戳分组为3分组后,确定连续的前2个值;例如,使用下表

Timestamp             Total
2013-10-11 00:01:00     1
2013-10-11 00:02:00     5
2013-10-11 00:03:00     6
2013-10-11 00:04:00     3
2013-10-11 00:05:00     9
2013-10-11 00:06:00     10
2013-10-11 00:07:00     12
2013-10-11 00:08:00     10
2013-10-11 00:09:00     15
2013-10-11 00:10:00     12

       .                .
       .                .

我必须将时间戳分组为3分钟组并显示每个3分钟组的最大总数的代码是

SELECT 
    max (Timestamp)
     AS tstamp
     max(total)
FROM table
Group by ROUND(UNIX_TimeStamp(timestamp)/180)

给出的输出是

 tstamp               max( Total)
2013-10-11 00:01:00       1
2013-10-11 00:04:00       6
2013-10-11 00:07:00       12
2013-10-11 00:10:00       15

       .                

我想在每3分钟组中添加前2个值,找到最大值,所以我得到了

tstamp               max( Total) Previous1  Previous2
2013-10-11 00:01:00       1          0         0
2013-10-11 00:04:00       6          5         1
2013-10-11 00:07:00       12         10        9
2013-10-11 00:10:00       15         10        12

       .                

我正在考虑一种方法是在嵌套选择中使用max(timestamp) - INTERVAL 1 MINUTE然后max(timestamp)-INTERVAL 2 MINUTE。这些方面的东西,但我不完全确定方法

是否有更简单/更清晰的方法来解决这个问题?

1 个答案:

答案 0 :(得分:1)

所以我从你拥有的东西开始:

select 
max(`Timestamp`) AS 'Timestamp'
,max(total) as total
, ROUND(UNIX_TimeStamp(`Timestamp`)/180) as roundBy3
FROM `time`
Group by ROUND(UNIX_TimeStamp(`Timestamp`)/180)
) summary

然后我添加了更多细节:

select `Timestamp`
, total
, ROUND(UNIX_TimeStamp(Timestamp)/180) as roundBy3
, @lastT3 := if(@lastT3 is null, 0, @lastT2) as saveForNext3
, @lastT2 := if(@lastT2 is null, 0, @lastT1) as saveForNext2
, @lastT1 := if(@lastT1 is null, 0, total) as saveForNext1

from `time`
, ( select @lastT1 := null
    , @lastT2 := null 
    , @lastT3 := null ) sqlvars
order by roundBy3 asc, total ASC

最后我把它们全部卷起来了:

select detail.Timestamp
, detail.total
, detail.saveForNext3
, detail.saveForNext2 
from (
    select 
    max(`Timestamp`) AS 'Timestamp'
    ,max(total) as total
    , ROUND(UNIX_TimeStamp(`Timestamp`)/180) as roundBy3
    FROM `time`
    Group by ROUND(UNIX_TimeStamp(`Timestamp`)/180)
    ) summary
join (
    select `Timestamp`
    , total
    , ROUND(UNIX_TimeStamp(Timestamp)/180) as roundBy3
    , @lastT3 := if(@lastT3 is null, 0, @lastT2) as saveForNext3
    , @lastT2 := if(@lastT2 is null, 0, @lastT1) as saveForNext2
    , @lastT1 := if(@lastT1 is null, 0, total) as saveForNext1

    from `time`
    , ( select @lastT1 := null
        , @lastT2 := null 
        , @lastT3 := null ) sqlvars
    order by roundBy3 asc, total ASC 
    ) detail
on summary.roundBy3 = detail.roundBy3 and summary.total = detail.total
group by ROUND(UNIX_TimeStamp(summary.Timestamp)/180);