日期:2014-05-18 浏览次数:20578 次
create proc test ( @begin datetime @endtime datetime ) as begin select 产品型号, sum(case when convert(varchar(7),添加时间,120)='2010-05' then 数量 else 0 end) as '2010-05', ..... from tb where 添加时间 between @begin and @endtime group by 产品型号 end
------解决方案--------------------
还缺了一个合计,补上。
CREATE PROCEDURE [dbo].[SelectByDate](@begin as DateTime, @end as DateTime)
AS
BEGIN
Declare @bs as varchar(50)
declare @es as varchar(30)
declare @res as varchar(4000)
declare @s as varchar(4000)
declare @temp as DateTime
set @bs = 'sum(case CONVERT(varchar(7),adddate, 120) when '
set @es = ' as '
set @s = ''
set @temp = @begin
while CONVERT(varchar(7), @temp, 120) <= CONVERT(varchar(7), @end, 120)
begin
set @res = @bs + quotename(convert(varchar(7),@temp, 120), '''') + ' then 1 else 0 end)' + @es + quotename(convert(varchar(7),@temp, 120), '''')
set @s = @s + ',' + @res
set @temp = dateadd(month, 1, @temp)
end
set @res = 'select productno' + @s + ', count(productno) as 总计 from productinfo where adddate between ' + quotename(convert(varchar,@begin), '''') + ' and ' + quotename(convert(varchar, @end), '''') + ' group by productno'
set @s = @res + ' union ' + 'select ''合计''' + @s + ', count(productno) as 总计 from productinfo where adddate between ' + quotename(convert(varchar,@begin), '''') + ' and ' + quotename(convert(varchar, @end), '''')
exec(@s)
END