首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

怎么通过指定时间段,得到该时间段的所有统计记录

2012-10-14 
如何通过指定时间段,得到该时间段的所有统计记录比如当月有有5条记录,我要显示这个月1号到30号的所有记录

如何通过指定时间段,得到该时间段的所有统计记录
比如当月有有5条记录,我要显示这个月1号到30号的所有记录最后得到的结果是30条,不是10条(见下表)
序号 金额 添加时间 用出时间 状态(是否已用)
 1 100 2012-6-1 null 0
 2 300 2012-6-3 null 0
 3 100 2012-6-5 2012-6-6 0
 4 100 2012-6-5 null 0
 5 100 2012-6-8 null 0

我想得到这个表
时间 到今天为止未用金额
2012-6-1 100
2012-6-2 100
2012-6-3 400
2012-6-4 400
2012-6-5 600
2012-6-6 500
2012-6-7 500
2012-6-8 600
........

我该怎么做..

[解决办法]

SQL code
--构建示例数据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 tableasreturnwith 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.TGROUP BY  O1.T, O1.金额ORDER BY  O1.T;/*时间         到今天为止未用金额---------- -----------2012-06-01 1002012-06-02 1002012-06-03 4002012-06-04 4002012-06-05 5002012-06-06 5002012-06-07 5002012-06-08 6002012-06-09 6002012-06-10 6002012-06-11 6002012-06-12 6002012-06-13 6002012-06-14 6002012-06-15 6002012-06-16 6002012-06-17 6002012-06-18 6002012-06-19 6002012-06-20 6002012-06-21 6002012-06-22 6002012-06-23 6002012-06-24 6002012-06-25 6002012-06-26 6002012-06-27 6002012-06-28 6002012-06-29 6002012-06-30 600(30 行受影响)*/ 

热点排行
Bad Request.