我想要做的是查找某人在星期日活动的连续周数并为其分配值。他们必须每天参加至少2场比赛,才能算上一周的比赛。
如果他们连续2周活跃,我想指定100,连续3周,值200,连续4周,值300,并持续连续9周。
我的困难不在于确定连续几周,而是在连续日期之间中断。假设以下数据集:
CustomerID RaceDate Races
1 2/2/2014 2
1 2/9/2014 5
1 2/16/2014 3
1 2/23/2014 3
1 3/2/2014 4
1 3/9/2014 3
1 3/16/2014 3
2 2/2/2014 2
2 2/9/2014 3
2 3/2/2014 2
2 3/9/2014 4
2 3/16/2014 3
CustomerID 1连续7周的价值为600。
对我来说困难的部分是CustomerID 2.他们将连续2周和连续3周。所以他们的总价值将是100 + 200 = 300。
我希望能够连续几周的任何不同组合来做到这一点。
请帮忙吗?
编辑:我正在使用SQL Server 2008 R2。
答案 0 :(得分:2)
在寻找顺序值时,有一个简单的观察有助于。如果从日期中减去序列,则该值为常量。您可以将其用作分组机制
select CustomerId, min(RaceDate) as seqStart, max(RaceDate) as seqEnd,
count(*) as NumDaysRaced
from (select t.*,
dateadd(week, - row_number() over (partition by customerID, RaceDate),
RaceDate) as grp
from table t
where races >= 2
) t
group by CustomerId, grp;
然后您可以使用它来获得最终的“积分”:
select CustomerId,
sum(case when NumDaysRaced > 1 then (NumDaysRaced - 1) * 100 else 0 end) as Points
from (select CustomerId, min(RaceDate) as seqStart, max(RaceDate) as seqEnd,
count(*) as NumDaysRaced
from (select t.*,
dateadd(week, - row_number() over (partition by customerID, RaceDate),
RaceDate) as grp
from table t
where races >= 2
) t
group by CustomerId, grp
) c
group by CustomerId;