有趣的問題。
這是一個使用有序分析函數和嵌套派生表的解決方案。 每個人的最終分數是在person_points。我使用分析函數sum()而不是分組,因爲我想顯示中間步驟。不應該統計與前一組重疊的3天期限的規則,這有點棘手。
create table t (person varchar(30), dt date);
insert into t values('John','2016-03-01');
insert into t values('John','2016-03-02');
insert into t values('John','2016-03-03');
insert into t values('John','2016-03-04');
insert into t values('John','2016-03-05');
insert into t values('David','2016-03-06');
insert into t values('David','2016-03-07');
insert into t values('David','2016-03-08');
insert into t values('David','2016-03-09');
insert into t values('David','2016-03-10');
insert into t values('David','2016-03-11');
insert into t values('John','2016-03-12');
insert into t values('John','2016-03-13');
insert into t values('John','2016-03-14');
insert into t values('John','2016-03-15');
insert into t values('John','2016-03-16');
insert into t values('John','2016-03-17');
insert into t values('John','2016-03-18');
insert into t values('John','2016-03-19');
insert into t values('David','2016-03-20');
insert into t values('Sue','2016-03-21');
insert into t values('Sue','2016-03-22');
insert into t values('Sue','2016-03-23');
insert into t values('Lily','2016-03-24');
insert into t values('Lily','2016-03-25');
insert into t values('Lily','2016-03-26');
insert into t values('Sue','2016-03-27');
insert into t values('David','2016-03-28');
insert into t values('John','2016-03-29');
insert into t values('David','2016-03-30');
insert into t values('John','2016-03-31');
select t_points.*
,sum(points) over(partition by person) person_points
from
(
select person, consecutive_group, min(dt) first_dt, max(dt) last_dt
, last_dt - first_dt + 1 n_days
,floor((n_days + 2)/3)*3 + first_dt - 1 end_of_3day_period
,max(end_of_3day_period) over(partition by person order by consecutive_group rows between 1 preceding and 1 preceding) prev_end_3day_dt
,case when prev_end_3day_dt >= first_dt then prev_end_3day_dt - first_dt + 1 else 0 end overlapped_days
,n_days - overlapped_days n_days_no_overlap
, floor((n_days_no_overlap + 2)/3) points
from
(
select person,dt
,sum(begin_new_consecutive) over(partition by person order by dt rows unbounded preceding) consecutive_group
from
(
select person, dt
,max(dt) over(partition by person order by dt rows between 1 preceding and 1 preceding) prev_dt
,case when dt = prev_dt+1 then 0 else 1 end begin_new_consecutive
from t
) t_consecutive
) t_consecutive_group
group by 1,2
) t_points
order by 1,2 ;
我刪除了MySQL的標籤,因爲它不屬於那裏。 –
我不明白你的數學。你能否清楚地解釋你作爲約翰的價值如何到達? –
由於添 以下是約翰 – Harry