2017-10-17 2 views
0

1つのIDの特定の変更のレコード(時間)を選択したいと思います。1つのIDの特定の変更のレコード(時間)を選択

のは、以下のデータセットを見てみましょう: - など25、複数のレコードがある場合> 24.

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のレコードを意味などは、25のスコア - > 24を選択し、最新のものを選択します。

これは役に立ちますか?

+1

いただきありがとうございますしかし、なぜない25から24からの変更? – Strawberry

+0

私は25 - > 24からの変更のみを気にするので、減額を意味します – antoinem

+0

あなたの質問に応じて編集してください – Strawberry

答えて

0

Hmmm。

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); 

しかし、それは、最終的なスコアは全て24電球いるのidのために動作しません:「25」を「24」に移動することが保証されている場合、これはほとんど動作します!最新の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); 

これは本当に楽しいものでした。これを行うための、より一般的な方法は、「次」の値を取得し、その後、いくつかの集約を行うことです。

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; 
+0

クール、それは私が欲しいものです、あなたの助けをありがとう。 – antoinem

0

ので、私は答えに前のポストに感謝を把握。

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

はあなたの助け

関連する問題