日期:2014-05-17 浏览次数:20585 次
--构建示例数据 create table #ta(序号 int, 金额 int, 添加时间 datetime, 用出时间 datetime, 状态 bit) insert into #ta select 1, 100, '2012-6-1', null, 0 union all select 2, 300, '2012-6-3', null, 0 union all select 3, 100, '2012-6-5', '2012-6-6', 1 union all select 4, 100, '2012-6-5', null, 0 union all select 5, 100, '2012-6-8', null, 0 --创建函数 Create function dbo.fn_MonthList(@s as datetime) returns table as return with CET1 AS (SELECT dateadd(dd, number , convert(char(6),@s,112)+'01')AS T FROM master..spt_values where type='p' and number < day(dateadd(mm,1,@s)-day(@s)) )SELECT * FROM CET1 GO --演示解决方案 ;with qq AS(select T, 金额 from dbo.fn_MonthList1('2012-06-09') a left join #ta b on b.添加时间 = a.T and 状态 <> 1) SELECT CONVERT(CHAR(10),O1.T,120) 时间, SUM(O2.金额) AS 到今天为止未用金额 FROM qq AS O1 JOIN qq AS O2 ON O2.T <= O1.T GROUP BY O1.T, O1.金额 ORDER BY O1.T; /*时间 到今天为止未用金额 ---------- ----------- 2012-06-01 100 2012-06-02 100 2012-06-03 400 2012-06-04 400 2012-06-05 500 2012-06-06 500 2012-06-07 500 2012-06-08 600 2012-06-09 600 2012-06-10 600 2012-06-11 600 2012-06-12 600 2012-06-13 600 2012-06-14 600 2012-06-15 600 2012-06-16 600 2012-06-17 600 2012-06-18 600 2012-06-19 600 2012-06-20 600 2012-06-21 600 2012-06-22 600 2012-06-23 600 2012-06-24 600 2012-06-25 600 2012-06-26 600 2012-06-27 600 2012-06-28 600 2012-06-29 600 2012-06-30 600 (30 行受影响) */