I have 2 SQL Server 2005 tables: Names
and Scores
Names table:
NameID, Name, Age
1, 'John', 23
2, 'Ryan', 20
Scores table:
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
I want to get开发者_如何学JAVA for a given month:
Name, Age, current ScoreValue, sum(ScoreValue) for previous months
Something like this form the month of february
:
John, 23, 300, 550
Ryan, 20, 350, 500
Think this is what you want:
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
精彩评论