步骤:
1.从表中查询数据,进行按日分组。
2.与临时表关联
Create table tb(日期 Varchar(10),时间 Varchar(10),价格 float)
insert tb values('2009-05-01','02:00:00','12.55')
insert tb values('2009-05-22','02:00:00','26.55')
insert tb values('2009-05-22','04:00:00','10.52')
insert tb values('2009-05-22','06:00:00','23.55')
insert tb values('2009-05-22','08:00:00','52.65')
insert tb values('2009-05-22','10:00:00','23.21')
insert tb values('2009-05-22','12:00:00','32.55')
insert tb values('2009-05-22','14:00:00','15.54')
insert tb values('2009-05-22','16:00:00','18.44')
insert tb values('2009-05-22','18:00:00','20.10')
insert tb values('2009-05-22','20:00:00','34.48')
insert tb values('2009-05-22','22:00:00','18.55')
insert tb values('2009-05-23','00:00:00','42.51')
insert tb values('2009-05-23','02:00:00','36.64')
insert tb values('2009-05-23','04:00:00','66.22')
insert tb values('2009-05-23','06:00:00','54.41')
select 日期,avg(价格) as 平均价格 from tb Group by 日期
GO
--创建一个存储过程
alter PROC UP_Con
@Year int, --年
@Month int --月
as
declare @Day int,@BeginDate datetime,@EndDate datetime,@i int
set @Day=Day(Convert(datetime,cast(@Year as Char(4))+'-'+cast(@Month+1 as VarChar(2))+'-01')-1) --当前月的天数
set @BeginDate=cast(@Year as Char(4))+'-'+cast(@Month as VarChar(2))+'-01' --开始今年
set @EndDate=Convert(datetime,cast(@Year as Char(4))+'-'+cast(@Month+1 as VarChar(2))+'-01')-1 --今年
--创建当前月临时表
create table #t(Date varchar(10))
set @i=1
while @i<=@Day
begin
--日期前加0,这个要根据数据的具体显示格式来定是否要加0,注意,不然会查不出数据
if @I<10
insert #t values(Convert(varchar(8),@BeginDate,120)+'0'+Cast(@I as char(1)))
else
insert #t values(Convert(varchar(8),@BeginDate,120)+Cast(@I as char(2)))
set @i=@i+1
end
--查询结束右连接临时表
;with a as(
select b.Date 日期,isnull(a.平均价格,0.000) 平均价格 from
(select 日期,avg(价格) as 平均价格 from tb Group by 日期) a right join #t b on a.日期=b.date
)
select * from a union all
select '合计',(select avg(nullif(平均价格,0)) from a)
GO
--调用
exec UP_Con 2009,5 --参数为要查询的年,月份