2013-08-25 47 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