我有2个 SQL Server 2005 表:Names
和Scores
名称表:
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 :(得分: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