简体   繁体   English

MySQL查询基于前一行的值

[英]mysql query based on value of previous row

I want to run a mysql query where the results are based on the value of the cell directly above the cell of interest. 我想运行一个mysql查询,其中结果基于所关注单元格正上方的单元格值。 For example: I am calculating time spent in a series of behaviors and would like to identify instances where the duration of time spent walking is longer than the time spent feeding that occurred immediately prior to walking. 例如:我正在计算花费在一系列行为上的时间,并想确定以下情况:步行所花费的时间比步行前所花费的进食时间要长。 Here is a sample data set: 这是一个示例数据集:

ID   Duration (min)  Time of Day    Behavior
1    21               9:01            Walk
1    31               9:22            Eat
1    15               9:53            Walk
1    21               10:14           Eat
2    7                1:00            Walk
2    9                1:07            Eat
2    4                1:16            Walk

I would like my query to identify the two rows in which the 'Duration' amount is smaller than for the previous row. 我希望查询确定“持续时间”量小于上一行的两行。 IE: the third entry for ID1, and the third entry for ID2. IE:ID1的第三个条目,ID2的第三个条目。

Any help would be greatly appreciated. 任何帮助将不胜感激。 Thx 谢谢

Sample data: 样本数据:

CREATE TABLE t
    (pkai int auto_increment primary key, `ID` int, `Duration` int, `TOD` time, `Behavior` varchar(4))
;

INSERT INTO t
    (`ID`, `Duration`, `TOD`, `Behavior`)
VALUES
    (1, 21, '9:01', 'Walk'),
    (1, 31, '9:22', 'Eat'),
    (1, 15, '9:53', 'Walk'),
    (1, 21, '10:14', 'Eat'),
    (2, 7, '01:00', 'Walk'),
    (2, 9, '01:07', 'Eat'),
    (2, 4, '01:16', 'Walk')
;

Note, that I added another column which is used as primary key (auto_increment). 请注意,我添加了另一列用作主键(auto_increment)。 It makes things less complicated here and you should have a primary key anyway. 它使事情变得不那么复杂,无论如何您都应该有一个主键。

Query: 查询:

select ID, Duration, TOD, Behavior from (
    select
    t.*,
    if(@prev_duration > Duration and @prev_id = ID, 1, 0) as prev_entry_longer,
    @prev_duration := if(@prev_id != ID, null, Duration),
    @prev_id := ID
    from
    t
    , (select @prev_duration := Duration, @prev_id := ID from t order by pkai limit 1) var_init
    where pkai != (select min(pkai) from t)
    order by ID, TOD
) sq
where prev_entry_longer = 1;

Result: 结果:

| ID | DURATION |                            TOD | BEHAVIOR |
|----|----------|--------------------------------|----------|
|  1 |       15 | January, 01 1970 09:53:00+0000 |     Walk |
|  2 |        4 | January, 01 1970 01:16:00+0000 |     Walk |
  • read more about user defined variables here . 在此处阅读有关用户定义变量的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM