查询截至某个日期的总和和日期之间的剩余值

tp5buhyn  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(416)

假设我有两张table如下
tbl\U播放器

player_id  int PK 
player_name varchar

tbl\U分数

score_id  int PK 
player_id int FK 
score_date date 
score int

我想查询的是两个日期之间每个球员的单日得分(每天1分)。我还想在比赛开始前得到球员的总得分。
t-sql查询是否可以实现这一点?

mepcadol

mepcadol1#

这对于窗口函数非常简单:

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

输出

+-----------+-------------+------------+-------+--------------------+
| player_id | player_name | score_date | score | score_before_start |
+-----------+-------------+------------+-------+--------------------+
|         1 |    Player 1 | 2020-06-01 |     2 |                  9 |
|         1 |    Player 1 | 2020-06-02 |     6 |                  9 |
|         2 |    Player 2 | 2020-05-31 |     6 |                  7 |
|         2 |    Player 2 | 2020-06-01 |     8 |                  7 |
|         2 |    Player 2 | 2020-06-02 |     6 |                  7 |
+-----------+-------------+------------+-------+--------------------+

相关问题