2011-03-24 67 views
0

我有2個SQL Server 2005的表:NamesScores計算先前的和值

名稱表:

NameID, Name, Age 
    1,  'John', 23 
    2,  'Ryan', 20 

成績表:

ScoreID, NameID, ScoreDate, ScoreValue 
    1,  1,  01/01/2011, 250 
    2,  1,  02/01/2011, 300 
    3,  1,  03/01/2011, 100 
    4,  2,  01/01/2011, 150 
    5,  2,  02/01/2011, 350 
    6,  2,  03/01/2011, 200 

我想獲得一個給定月份:

Name, Age, current ScoreValue, sum(ScoreValue) for previous months

事情是這樣的形式的february月:

John, 23, 300, 550 
Ryan, 20, 350, 500 
+0

位,你被困在哪 - 的加入,聚合,找到最新的,過濾一個月?我也沒有看到你從哪裏獲得總數 - 每個球員只有2月份的記錄? – Rup 2011-03-24 11:58:39

+0

我想獲得所有以前的值(包括當前月份在內的所有以前的日期)的總和。 – milo2011 2011-03-24 12:08:17

回答

0

認爲這是你想要什麼:

select n.Name, 
     s1.ScoreId, 
     s1.nameId, 
     s1.ScoreValue, 
     sum(s2.ScoreValue) Prevmonths 
from names n 
     inner join scores s1 on n.NameId = s1.NameId 
     left join scores s2 -- make left join in case no previous month 
     on s1.NameId = s2.NameId 
     and s1.ScoreDate >= s2.ScoreDate -- >= means include current onth 
group by n.Name, 
     s1.ScoreId, 
     s1.nameId, 
     s1.ScoreValue 

GJ

+0

謝謝!我已經使用了你的腳本的一部分。 – milo2011 2011-03-24 12:17:29