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

时间:2017-10-17 21:14:27

标签: sql sql-server aggregate-functions

我想选择一个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

我想返回&#39; 201512&#39;,表示Id = 1的记录,例如得分25 - &gt; 24.如果有多个记录使得25 - > 24然后选择最新的一个。

任何可以提供帮助吗?

2 个答案:

答案 0 :(得分:0)

嗯。如果“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);

但这对于最终得分都是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);

这一切真的只是为了好玩。更典型的方法是获取“下一个”值,然后进行一些聚合:

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;

答案 1 :(得分: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

感谢您的帮助