补全日期的SQL语句,你会么
if object_id('tempdb.dbo.#TA') is not null drop table #TA go
create table #TA([DT] datetime,[Qty] int)
insert #TA select '2009-12-23',5
union allselect '2010-01-20',1
union allselect '2010-01-25',2
union allselect '2010-01-26',3
union allselect '2010-02-27',4
union allselect '2010-03-25',5
union allselect '2010-12-26',100
union allselect '2011-01-23',6
union allselect '2011-01-25',7
union allselect '2011-02-03',8
union allselect '2011-03-03',9
union allselect '2011-03-25',10
union allselect '2011-03-26',11
;WITH CET AS
(
select case when datepart(DD,dt)>25 then convert(varchar(7), DATEADD(MM,2,dt),120) + '-25'
else convert(varchar(7), DATEADD(MM,1,dt),120) + '-25' end as YM, SUM(Qty) SumQty
from #TA
group by case when datepart(DD,dt)>25 then convert(varchar(7), DATEADD(MM,2,dt),120) + '-25'
else convert(varchar(7), DATEADD(MM,1,dt),120) + '-25' end
)
SELECT O1.YM, SUM(O2.SumQty) AS totalqty
FROM CET AS O1
JOIN CET AS O2
ON O2.YM <= O1.YM and o2.YM>dateadd(month,-12,o1.YM)
GROUP BY O1.YM
ORDER BY O1.YM;
----------------结果----------------------------
/*
YM totalqty
---------- -----------
2010-01-25 5
2010-02-25 8
2010-03-25 11
2010-04-25 20
2011-02-25 125
2011-03-25 130
2011-04-25 140
2011-05-25 151
这里的结果日期如果没出现的能帮我不全么,求的是12个月内的数量和。比如结果应该有2010-05-25也应该有个20,求的是2009-04-26到2010-04-25的数量和。这里中间所有没出现过的日期(每个月的25号)都要补全,相当于上面的日期和一个循环的日期求和,那个表的totalQty为0,日期应该between最小的,最大的。帮我补全代码好么
------解决方案--------------------计算2个日期(d1、d2)间隔的天数n
根据序号表生成一个n条记录的记录集
select @d1+a.i fdate
from 某个系统表 a
where a.i>=0 and a.i<n