繁体   English   中英

选择一个ID的特定更改的记录(时间)

[英]SELECT the record (time) of a specific change for one ID

我想为一个ID选择特定更改的记录(时间)。

让我们采用以下数据集:

    Date         Id       Score
--------------------------------------------
   201508         1           24
   201509         1           24
   201510         1           25
   201511         1           25
   201512         1           24    <-- return this value
   201601         1           25
   201508         2           25
   201509         2           25

我想返回'201512',表示Id = 1的记录,例如Score 25->24。如果有多个记录,例如25-> 24,则选择最新的记录。

有什么可以帮助的吗?

如果保证将“ 25”设置为“ 24”,则几乎可以使用:

select id,
       max(case when score = 25 then date end) 
from t
group by id
having max(case when score = 25 then date end) < max(case when score = 24 then date end);

但这对于id的最终分数全为24的id无效。 选择所有小于或等于最近24个日期的日期:

select id,
       max(case when score = 25 then date end) 
from t
where date <= (select max(t2.date) where t2.id = t.id and t2.score = 24)
group by id
having max(case when score = 25 then date end) < max(case when score = 24 then date end);

所有这些实际上只是为了好玩。 更典型的方法是获取“ next”值,然后进行一些聚合:

select id, max(date)
from (select t.*,
             (select t2.score
              from t t2
              where t2.id = t.id and t2.date > t.date
              order by t.date
              limit 1
             ) as next_score
      from t
     ) t
where score = 25 and next_score = 24
group by id;

所以我感谢上一篇文章的答案。

SELECT t1.Id , MAX(t2.Score) Max FROM table t1 LEFT JOIN table t2 ON t1.Id= t2.Id AND DATEFROMPARTS(LEFT(t1.Date, 4), RIGHT(t1.Date, 2) , 1) = DATEADD(mm, -1, DATEFROMPARTS(LEFT(t2.Date, 4), RIGHT(t2.Date, 2) , 1)) WHERE t1.Score = 25 AND t2.Score = 24 GROUP BY t1.Id, t2.Score

谢谢您的帮助

暂无
暂无

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

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