-- Create some dummy data
declare @TBL_PLAYER table(player_id int,player_name varchar(20));
declare @TBL_SCORE table(score_id int,player_id int,score_date date,score int);
insert into @TBL_PLAYER values(1,'Player 1'),(2,'Player 2');
insert into @TBL_SCORE values(1,1,getdate()-6,3),(2,1,getdate()-5,6),(3,1,getdate()-3,2),(4,1,getdate()-2,6),(5,1,getdate()-1,8),(6,2,getdate()-5,7),(7,2,getdate()-4,6),(8,2,getdate()-3,8),(9,2,getdate()-2,6),(10,2,getdate()-1,1);
-- Query
declare @StartDate datetime = '20200531';
declare @EndDate datetime = '20200602';
with s as
(
select s.player_id
,s.score_date
,s.score
-- Calculate a running total of the scores up to @StartDate for each player
,sum(case when s.score_date < @StartDate then s.score else 0 end) over (partition by s.player_id) as score_before_start
from @TBL_SCORE as s
where s.score_date <= @EndDate -- Only interested in data before @EndDate
)
select p.player_id
,p.player_name
,s.score_date
,s.score
,s.score_before_start
from s
join @TBL_PLAYER as p
on s.player_id = p.player_id
where score_date >= @StartDate
order by player_id
,score_date;
1条答案
按热度按时间mepcadol1#
这对于窗口函数非常简单:
输出