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

时间段分组统计解决方法

2012-01-19 
时间段分组统计表Asysdatetimevalue2007-09-031002007-09-0420......2007-09-20300如何显示时间段总数2003

时间段分组统计
表A
sysdatetime   value
2007-09-03         100
2007-09-04         20
......
2007-09-20         300

如何显示
      时间段                                   总数
2003-09-03   至   2007-9-05         500
2003-09-06   至   2007-9-08         600
......

[解决办法]
declare @a table(a varchar(10),value int)
insert @a select '2007-09-03 ', 100
union all select '2007-09-04 ', 20
union all select '2007-09-05 ', 20
union all select '2007-09-06 ', 20
union all select '2007-09-07 ', 20
union all select '2007-09-08 ', 20
union all select '2007-09-09 ', 20
union all select '2007-09-10 ', 20
union all select '2007-09-11 ', 20
union all select '2007-09-12 ', 20
union all select '2007-09-13 ', 20
union all select '2007-09-14 ', 20
union all select '2007-09-15 ', 20
union all select '2007-09-16 ', 20
union all select '2007-09-17 ', 20
union all select '2007-09-18 ', 20
union all select '2007-09-19 ', 20
union all select '2007-09-20 ', 300

select b.a+ ' 至 '+convert(varchar(10),b.c, 120) 时间段,sum(case when a.a between.b.a and b.c then a.value else 0 end) 总数 from @a a,(
select b.*,dateadd(day,2,b.a) c from (select min(a) a,max(a) b from @a) a,@a b where datediff(day,a.a,b.a)*1.0/3=cast(datediff(day,a.a,b.a)/3 as int)
)b
group by b.a,b.c
--result
/*
时间段 总数
------------------------ -----------
2007-09-03 至 2007-09-05 140
2007-09-06 至 2007-09-08 60
2007-09-09 至 2007-09-11 60
2007-09-12 至 2007-09-14 60
2007-09-15 至 2007-09-17 60
2007-09-18 至 2007-09-20 340
*/

热点排行