sql 相对于另一列的最小日期

sql min date with respect to another column

我遇到这种情况:2列

score   date
-1      09/02/2018
-1      08/02/2018
-1      07/02/2018
 2      06/02/2018
 2      05/02/2018
 2      04/02/2018
-1      02/02/2018
-1      01/02/2018

如何获取上次得分的最小日期 -1? 我需要获取日期:07/02/2018

您可以使用:

select min(t.date)
from t
where t.score = -1 and
      t.date > (select max(t2.date) from t t2 where t2.score <> -1);

这 returns 您数据中最新系列 -1 的最旧日期:

SELECT Max(dt)
FROM
 ( -- find all the rows starting a new series of -1
   SELECT datecol as dt, 
      Min(score) -- score of previous date
      Over (ORDER BY datecol DESC
            ROWS BETWEEN 1 Following AND 1 Following) AS prev_score
   FROM tab  
   QUALIFY score = -1                               -- current score must be -1 
       AND (prev_score <> -1 OR prev_score IS NULL) -- and previous score either <> -1 or NULL (data starts with -1)
 ) AS dt

如果您有多个组,您可以添加 PARTITION BY 和 GROUP BY。