一個關於日期統計較難的問題,請大俠們幫助看看,應該這樣做?謝
一個較難的問題,請大俠們幫助看看:
現有表結構:
Prod_no prod_spec sf_1 date
136-1 a1 20 2008/06/05
136-1 a1 11 2008/06/09
136-1 a2 5 2008/06/03
137-1 a1 15 2008/08/05
137-1 a3 45 2008/08/11
如要查找136-1這個料號6月份每天的數據,顯示為如下形式
Prod_spec 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
a1 0 0 0 0 20 0 0 0 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
a2 0 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
如要查找137-1這個料號8月份每天的數據,顯示為如下形式
Prod_spec 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
a1 0 0 0 0 15 0 0 0 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
a3 0 0 0 0 0 0 0 0 0 0 45 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
問題點:
1、根據提供的料號及時段統計此時段內從開始的第一天到月未每天的數據並且橫向顯示,如沒有數據以0表示
2、如果分開做,我知道怎麼做,但我想用一個存諸過程實現,但我試了很久,都實現不了,請大俠們幫助,具體應怎樣才能實現?謝謝
[解决办法]
--建立测试环境
create table tb(Prod_no nvarchar(10), prod_spec nvarchar(10), sf_1 int, date datetime)
insert tb select '136-1 ', 'a1 ', 20, '2008/06/05 '
union all select '136-1 ', 'a1 ', 11, '2008/06/09 '
union all select '136-1 ', 'a2 ', 5, '2008/06/03 '
union all select '137-1 ', 'a1 ', 15, '2008/08/05 '
union all select '137-1 ', 'a3 ', 45, '2008/08/11 '
go
--创建存储过程
create procedure sp_count
@Prod_no nvarchar(10),
@date datetime
as
begin
declare @date_start datetime,
@date_end datetime,
@daysOfMonth int,
@sql nvarchar(4000)
select @date_start =convert(char(7), @date, 120)+ '-01 ',
@date_end = convert(char(7), dateadd(month,1,@date), 120)+ '-01 '
set @daysOfMonth = datediff(day,@date_start,@date_end)
set @date_end = dateadd(ms,-1,@date_end) --结束时间改为当月最后一毫秒
set @sql= ' select prod_spec '
declare @n varchar(2)
set @n= '1 '
while cast(@n as int) <=@daysOfMonth
begin
set @sql = @sql + ', [ ' + @n + ']= sum(case datepart(day,date) when ' + @n + ' then sf_1 else 0 end) '
set @n = ltrim(cast(@n as int)+1)
end
set @sql = @sql + ' from tb where Prod_no= ' ' ' + @Prod_no + ' ' ' and date between ' ' ' + cast(@date_start as nvarchar(20)) + ' ' ' and ' ' ' + cast(@date_end as nvarchar(20)) + ' ' ' '
set @sql = @sql + ' group by prod_spec '
exec(@sql)
end
go
--测试存储过程
declare @Prod_no nvarchar(10),
@date1 datetime
select @Prod_no= '136-1 ', @date1= '2008/06/22 '
exec dbo.sp_count @Prod_no, @date1
select @Prod_no= '137-1 ', @date1= '2008/08/01 '
exec dbo.sp_count @Prod_no, @date1
go
--删除表及存储过程
drop table tb
drop procedure sp_count