简体   繁体   中英

selection based on previous row value

I need to select all entities whom props were changed from 4 to 5.

Example:
T1 (It is action log table)

entity      dt            prop
4           2017-03-01    0
4           2017-03-02    1  
4           2017-03-03    4
4           2017-03-04    5
4           2017-03-05    1
4           2017-03-06    1
4           2017-03-07    1

Now I do it with script. First I select entities (and their dt) which have prop=5, then select preceding record (based on dt) for each entity, and if prop is 4 then entity are included to report.

Is it possible to do in one SQL query?

One method uses a correlated subquery:

select entity
from (select t.*,
             (select t2.prop
              from t t2
              where t2.entity = t.entity and t2.dt < t.dt
              order by t2.dt desc
              limit 1
             ) as prev_prop
      from t
      where prop = 5
     ) t
where prev_prop = 4;

If you like, you can make use of MySQL's extension of having to eliminate the outer query:

select t.*,
       (select t2.prop
        from t t2
        where t2.entity = t.entity and t2.dt < t.dt
        order by t2.dt desc
        limit 1
       ) as prev_prop
from t
where prop = 5
having prev_prop = 4;

Note: there may be more efficient ways to implement this. For instance, if each entity has at most one 4 and one 5 and no other props are expected in between, then you can do:

select entity
from t
group by entity
having max(case when prop = 4 then dt end) < max(case when prop = 4 then dt end);

Use a self-join:

SELECT a.*
FROM T1 AS a
JOIN T1 AS b ON a.entity = b.entity AND a.dt = DATE_ADD(b.dt, INTERVAL 1 DAY) 
WHERE a.prop = 5 AND b.prop = 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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