基于先前行值的选择

时间:2018-03-30 12:01:39

标签: mysql sql

我需要选择道具从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查询中执行?

2 个答案:

答案 0 :(得分:0)

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

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;

注意:可能有更有效的方法来实现它。例如,如果每个实体最多只有一个4和一个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);

答案 1 :(得分:0)

使用自我加入:

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