查询总计日期和日期之间的剩余数

时间:2020-06-04 07:52:52

标签: sql sql-server tsql

假设我有两个如下表

TBL_PLAYER

player_id  int PK 
player_name varchar

TBL_SCORE

score_id  int PK 
player_id int FK 
score_date date 
score int

我想查询的是两个日期之间的每一天每个玩家的分数(每天1个分数)。我也想在比赛开始前获得球员的总分。

使用T-SQL查询是否有可能?

1 个答案:

答案 0 :(得分:2)

使用窗口功能非常简单:

parameter sweep

输出

-- 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;