insert into table1 values(1,'2002-5-25',145774,1,1001)
insert into table1 values(2,'2003-4-29',14588,2,1001)
insert into table1 values(3,'2005-5-12',125664,3,1003)
insert into table1 values(4,'2002-1-22',645555,5,1002)
insert into table1 values(5,'2005-2-22',64457,1,1004)
insert into table1 values(6,'2005-8-22',64457,1,1004)
insert into table1 values(7,'2005-4-22',64457,1,1004)
insert into table1 values(8,'2005-12-22',64457,1,1004)
insert into table1 values(9,'2005-6-22',64457,2,1004)
insert into table1 values(10,'2005-9-22',64457,2,1004)
insert into table1 values(11,'2005-11-22',64457,4,1004)
go
select tid, year(ttime)as years,month(ttime) as months,balance,yyt,person into table3 from table1
go
select *from table3
go
select t3.*, (t3.months1+t3.months2+t3.months3+t3.months4+t3.months5) as sumprice,
(t3.months1+t3.months2+t3.months3+t3.months4+t3.months5)/5 as avgprice
from(select years ,
sum( case t.months when 1 then balance else 0 end) as months1,
sum(case t.months when 2 then balance else 0 end) as months2,
sum (case t. months when 3 then balance else 0 end )as months3,
sum (case t.months when 4 then balance else 0 end) as months4,
sum (case t.months when 5 then balance else 0 end) as months5
from table3 as t
group by t.years) as t3