2013-08-25 50 views
1

我有数据的两个表:的Oracle SQL:基于列的累积总数值

  • TableA的保持日期和体育比赛期间进行分数的时间;和保持比赛的日期和哪支球队数分别在主场和客场的球队
  • 表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

的这个困难的部分是不累积和分析功能。它正在获得表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分)。

+0

伟大的解决方案戈登! +1 – MrSimpleMind

+0

很好的答案,但是对damo的笔记。考虑一天中可能会有多个游戏。由于您将match_date存储为数字,因此为了以防万一,请在结尾处再添加一位数字。 –

+0

大戈登,谢谢!完全按照需要工作。对不起所需的输出数据不正确。罗伯特,感谢一天中两场比赛的领先。 – Damo