统计报表
有一表格式为: 
 日期                                 余额                     科目 
 2006-12-29            1000.00     1111 
 2006-12-30            1000.00     1111 
 2006-12-31            1000.00     1111 
 2007-01-01            4000.00     1111 
 2007-01-02            8000.00     1111 
 2007-01-03            9000.00     1111 
 2007-01-04            10000.00  1111 
 根据日期和科目,比如根据日期为2007-01-03和科目1111,select出: 
    余额               比上月               比上年               比上日               年平均                
 9000.00         8000.00            8000.00            1000.00               (4000+8000+9000)/3=7000.00 
 数据很多,到2月份时也要统计出这一张表,请帮忙给出一个解决的办法,谢谢!     
------解决方案--------------------create table T(日期 datetime, 余额 decimal(10,2), 科目 varchar(10)) 
 insert T select  '2006-12-29 ', 1000.00,  '1111 ' 
 union all select  '2006-12-30 ', 1000.00,  '1111 ' 
 union all select  '2006-12-31 ', 1000.00,  '1111 ' 
 union all select  '2007-01-01 ', 4000.00,  '1111 ' 
 union all select  '2007-01-02 ', 8000.00,  '1111 ' 
 union all select  '2007-01-03 ', 9000.00,  '1111 ' 
 union all select  '2007-01-04 ', 10000.00,  '1111 '   
 declare @dt datetime 
 set @dt =  '2007-01-03 ' 
 select  
 余额, 
 比上月=余额-isnull((select 余额 from T where 科目= '1111 ' and 日期=dateadd(month, -1, @dt)), 0), 
 比上年=余额-isnull((select 余额 from T where 科目= '1111 ' and 日期=dateadd(year, -1, @dt)), 0), 
 比上日=余额-isnull((select 余额 from T where 科目= '1111 ' and 日期=@dt-1), 0), 
 年平均=(select avg(余额) from T where 科目= '1111 ' and year(日期)=year(@dt) and 日期 <=@dt) 
 from T 
 where 日期=@dt and 科目= '1111 '
------解决方案--------------------我想建一个procedure更合楼主的意思. 楼主只要输入日期和科目的名称就能得到想要的结果.
------解决方案--------------------你是按月统计的还是按天统计的?说明白点可不可以啊?
------解决方案--------------------create table T(日期 datetime, 余额 decimal(10,2), 科目 varchar(10),部门号 int) 
 insert into T  
 select  '2006-12-31 ',2000.00,1111,2 
 union all 
 select  '2006-12-31 ',1000.00,1111,1 
 union all 
 select  '2007-01-01 ',4000.00,1111,1 
 union all 
 select   '2007-01-02 ',8000.00,1111,1 
 union all 
 select  '2007-01-03 ',9000.00,1111,1 
 union all 
 select  '2007-01-04 ',10000.00,1111,1 
 union all 
 select  '2007-01-01 ',4000.00,1111,2 
 union all 
 select  '2007-01-02 ',8000.00,1111,2 
 union all 
 select  '2007-01-03 ',9000.00,1111,2 
 union all 
 select  '2007-01-04 ',10000.00,1111,2   
 create table D(部门号 int,部门名称 varchar(10)) 
 insert into D 
 select 1, '部门1 ' 
 union all 
 select 2, '部门2 ' 
 --select * from T 
 --select * from D 
 alter procedure dbo.Proc_display(@dt datetime,@kemu varchar(10)) 
 as 
 begin 
 	select a.部门号,D.部门名称, 
 	余额=(select top 1 余额 from T where 日期 <@dt and 科目=@kemu and 部门号=D.部门号 order by 日期 desc ), 
 	比上月=((select top 1 余额 from T where 日期 <@dt and 科目=@kemu and 部门号=D.部门号 order by 日期 desc )-(select t