create table User_Salary (UserName nvarchar(200), Month nvarchar(20), Salary int)
go
insert into User_Salary (UserName,Month,Salary ) values('AAA','2010/12',1000)
insert into User_Salary (UserName,Month,Salary ) values('AAA','2011/01',2000)
insert into User_Salary (UserName,Month,Salary ) values('AAA','2011/02',3000)
insert into User_Salary (UserName,Month,Salary ) values('BBB','2010/12',2000)
insert into User_Salary (UserName,Month,Salary ) values('BBB','2011/01',2500)
insert into User_Salary (UserName,Month,Salary ) values('BBB','2011/02',2500)
上面是原表格,想實現成(UserName相同,根據日期降序進行匯總,即匯總日期小於此行日期且UserName相同所有數據),如下圖
該如何寫SQL語句
select u.*
,(select SUM(salary) from User_Salary where User_Salary.Month<=u.month and User_Salary.UserName = u.userName) as 總和
from User_Salary u