简体   繁体   中英

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

I would like to SELECT the record (time) of a specific change for one ID.

Let's take the following dataset:

    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

I would like to return '201512', meaning the record of Id = 1 such as Score 25 -> 24. If there are multiple records such that 25 -> 24 then select the latest one.

Any could help on this?

Hmmm. This will almost work, if the "25" is guaranteed to go to "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);

But that doesn't work for id's where the final scores are all 24. Lightbulb! Choose all dates which are less than or equal to the most recent 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);

All that was really just for fun. The more typical way of doing this is to get the "next" value and then do some aggregation:

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;

so I figure out the answer thanks to the previous post.

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

Thank you for your help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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