[英]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.