繁体   English   中英

根据上一行值进行选择

[英]selection based on previous row value

我需要选择道具从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

现在我用脚本来做。 首先,我选择prop = 5的实体(及其dt),然后为每个实体选择先前的记录(基于dt),如果prop为4,则包括实体以进行报告。

是否可以在一个SQL查询中执行?

一种方法使用相关子查询:

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;

如果你喜欢,你可以使用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;

注意:可能会有更有效的方法来实现此目的。 例如,如果每个实体最多具有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);

使用自联接:

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