簡體   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