我有两个数据表:
表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;
答案 0 :(得分: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;
Here是SQL小提琴。
顺便说一下,根据您的数据,20130818
的最后一个值应为7
而不是6
(得分为2分)。