有个保养计划设定表如下:
ID 保养周期 (天) 最后保养日期
A 3 2014-5-1
B 7 2014-5-2
C 15 2014-5-2
D 30 2014-5-1
要求生成5月份保养计划
说明:用0表示无计划,用1表有计划
ID 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16.....28 29 30 31
A 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1
B 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0
C 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1
D 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0......0 0 0 1
请问用SQL如何生成?
------解决方案--------------------
if object_id('tempdb..#temp') is not null
begin
drop table #temp
end
create table #temp
( [id] [nvarchar](50) NULL,
[day] int NULL,
[type] int
);
declare @day int
DECLARE @id [nvarchar]
DECLARE @cycle int
DECLARE @lasttime date
DECLARE cursor1 CURSOR FOR
SELECT * FROM [plan]
OPEN cursor1
FETCH NEXT FROM cursor1 INTO @id,@cycle,@lasttime
WHILE @@FETCH_STATUS = 0
BEGIN
set @day=datepart(dd,@lasttime)
insert into #temp select @id,@day,1
while @day+@cycle <= 31
begin
set @day=@day+@cycle
insert into #temp select @id,@day,1
end
FETCH NEXT FROM cursor1 INTO @id,@cycle,@lasttime
end
CLOSE cursor1
DEALLOCATE cursor1
select * from #temp
pivot(sum([type]) for [day] in ([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])) as pvt