1

我有两个数据表:

  • 表 A 保存体育比赛期间得分的日期和时间;和
  • 表B,其中包含比赛日期以及哪些球队号码是主队和客队

表A

Date        Time    Team    Points_scored
-----------------------------------------
20130818    1400    1       2
20130818    1402    1       3
20130818    1407    2       2
20130818    1410    2       3
20130818    1412    1       2
20130822    1550    4       2
20130822    1552    5       3
20130822    1553    5       2
20130822    1555    5       3
20130822    1559    4       2

表B

Date        Home Team   Away Team
-----------------------------------------------------
20130818    2           1
20130822    4           5

我想要的是一个查询,它为每天的主队和客队提供运行总数,如下所示:

Date        Time    Home_score    Away_score
20130818    1400    0             2
20130818    1402    0             5
20130818    1407    2             5
20130818    1410    5             5
20130818    1412    5             6
20130822    1550    2             0
20130822    1552    2             3
20130822    1553    2             5
20130822    1555    2             8
20130822    1559    4             8

但我什至不确定从哪里开始。有没有人有任何想法?我正在使用 Oracle 11g。

非常感谢。

这是创建脚本:

create table tablea (
    match_date            number,
    time            number,
    team            number,
    points_scored   number);

create table tableb (
    match_date        number,
    home_team   number,
    away_team   number);

insert into tablea values (20130818,1400,1,2);
insert into tablea values (20130818,1402,1,3);
insert into tablea values (20130818,1407,2,2);
insert into tablea values (20130818,1410,2,3);
insert into tablea values (20130818,1412,1,2);
insert into tablea values (20130822,1550,4,2);
insert into tablea values (20130822,1552,5,3);
insert into tablea values (20130822,1553,5,2);
insert into tablea values (20130822,1555,5,3);
insert into tablea values (20130822,1559,4,2);

insert into tableb values (20130818,2,1);
insert into tableb values (20130822,4,5);

commit;
4

1 回答 1

4

困难的部分不是累积和分析函数。它正在正确地连接表 a 和表 b。

select b.match_date, a.time,
       (case when a.team = b.home_team then a.points_scored else 0 end) as home_points,
       (case when a.team = b.away_team then a.points_scored else 0 end) as away_points,
       sum(case when a.team = b.home_team then a.points_scored else 0 end) over (partition by a.match_date order by a.time) as cum_home_points,
       sum(case when a.team = b.away_team then a.points_scored else 0 end) over (partition by a.match_date order by a.time) as cum_away_points
from TableB b join
     TableA a
     on a.team in (b.home_team, b.away_team) and b.match_date = a.match_date;

是 SQL 小提琴。

顺便说一句,根据您的数据,最后一个值20130818应该是7而不是6(得 2 分)。

于 2013-08-25T12:47:51.547 回答