如何统计每个月份的销售额??高手请进
例如一组数据:
(金额)amt (销售时间)date
500 2006-10-13
700 2007-2-19
200 2007-3-12
300 2007-3-13
100 2007-4-2
400 2007-5-23
500 2007-5-31
700 2007-8-12
800 2007-8-15
要得到的数据为2006年10到2007年8月每个月的销售额:
总金额 月份
500 2006-10
0 2006-11
0 2006-12
0 2007-1
700 2007-2
500 2007-3
100 2007-4
900 2007-5
0 2007-6
0 2007-7
1500 2007-8
------解决方案--------------------借用下臨時表
Select TOP 100 ID = Identity(Int, 0, 1) Into #T From SysColumns A, SysObjects B
Declare @Max DateTime, @Min DateTime
Select @Max = Max(销售时间), @Min = Min(销售时间) From TEST
Select
IsNull(SUM(B.金额), 0) As 总金额,
A.月份
From
(Select
Convert(Varchar(7), DateAdd(mm, ID, @Min), 120) As 月份
From
#T
Where ID <= DateDiff(mm, @Min, @Max)) A
Left Join
TEST B
On
A.月份 = Convert(Varchar(7), B.销售时间, 120)
Group By
A.月份
Order By
A.月份
------解决方案----------------------建立测试环境
create table #tb(amt int,date smalldatetime)
insert #tb(amt,date)
select '500 ', '2006-10-13 ' union all
select '700 ', '2007-2-19 ' union all
select '200 ', '2007-3-12 ' union all
select '300 ', '2007-3-13 ' union all
select '100 ', '2007-4-2 ' union all
select '400 ', '2007-5-23 ' union all
select '500 ', '2007-5-31 ' union all
select '700 ', '2007-8-12 ' union all
select '800 ', '2007-8-15 '
go
create function dbo.f_getmonth(@begin_date datetime,@end_date datetime)
returns @t table(mm varchar(7))
as
begin
insert @t
select convert(char(7),@begin_date,120)
while datediff(mm,@begin_date,@end_date) > 0
begin
set @begin_date = dateadd(mm,1,@begin_date)
insert @t
select convert(char(7),@begin_date,120)
end
return
end
go
--