简体   繁体   English

根据上一行值进行选择

[英]selection based on previous row value

I need to select all entities whom props were changed from 4 to 5. 我需要选择道具从4变为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. 首先,我选择prop = 5的实体(及其dt),然后为每个实体选择先前的记录(基于dt),如果prop为4,则包括实体以进行报告。

Is it possible to do in one SQL query? 是否可以在一个SQL查询中执行?

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: 如果你喜欢,你可以使用MySQL的延伸的having消除外部查询:

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: 例如,如果每个实体最多具有1个4和1个5,并且在它们之间不期望其他道具,则可以执行以下操作:

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

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

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