如何计算没有日期差距的最长和最新连胜

时间:2016-10-24 14:01:25

标签: sql sql-server sql-server-2008

我想计算没有日期差距的最长和最新连胜。我正在使用SQL Server 2008.我有一个像这样的表结构:

Date       Result  Value   
2014-01-14  W   1800
2014-10-08  L   900
2014-10-17  L   900
2015-04-15  L   900
2015-07-23  W   1800
2016-01-04  L   900
2016-05-31  L   195
2016-06-01  W   6351
2016-06-02  W   10500
2016-06-03  L   312
2016-06-14  W   14091
2016-06-27  W   3360
2016-07-11  W   4320
2016-07-12  W   55596
2016-07-13  W   14403
2016-08-04  W   86399
2016-09-13  L   356
2016-10-09  W   86399
2016-10-10  W   177178
2016-10-18  W   86399
2016-10-19  W   86399

输出

 Streak Total    RecordType
    2   172798   Latest             //Comments (2016-10-18,2016-10-19)
    3   74319    Longest            //Comments(2016-07-11,2016-07-12,2016-07-13)

1 个答案:

答案 0 :(得分:4)

您可以通过从日期中减去递增数字来识别条纹。如果这是恒定的,那么你就有了条纹:

select min(date) as winning_streak_start, count(*) as num_days, sum(value) as total
from (select t.*, dateadd(day, -row_number() over (order by date), date) as grp
      from t
      where result = 'W'
     ) t
group by grp;

然后您可以使用它来获得最长和最近的:

with t as (
      select min(date) as winning_streak_start, count(*) as streak, sum(value) as total
      from (select t.*, dateadd(day, -row_number() over (order by date), date) as grp
            from t
            where result = 'W'
           ) t
      group by grp
     )
select t.*
from ((select top (1) streak, total, 'Longest' as RecordType
       from t
       order by streak desc
      ) union all
      (select top (1) streak, total, 'Latest'
       from t
       order by winning_streak_start desc
      )
     ) t;