日期:2014-05-17  浏览次数:20653 次

时间分段查询,每段时间获取另一字段为最小的时间
还是之前提问过的
http://bbs.csdn.net/topics/390277980
需求发生了变化
首先是原始表增加了Num字段
doer dotime        num
 a 2012-1-1 0:09    12.2
 a 2012-1-1 1:09 12.6
 a 2012-1-1 2:09 11.9
 a 2012-1-1 3:09 9.6
 a 2012-1-1 4:09 12.6
 a 2012-1-1 5:09 11.9
 a 2012-1-1 6:09 9.6
 a 2012-1-1 7:09 12.6
 a 2012-1-1 8:09 11.9
 a 2012-1-1 9:09 9.6
 a 2012-1-1 10:09 12.6
 a 2012-1-1 11:09 11.9
 a 2012-1-1 12:09 9.6
 a 2012-1-1 13:09 12.6
 a 2012-1-1 14:09 11.9
 a 2012-1-1 15:09 9.6
 a 2012-1-1 16:09 9.6
 a 2012-1-1 17:09 12.6
 a 2012-1-1 18:09 11.9
 a 2012-1-1 19:09 9.6
 a 2012-1-1 20:09 12.6
 a 2012-1-1 21:09 11.9
 a 2012-1-1 22:09 9.6
 a 2012-1-1 23:09 12.6
 b 2012-1-1 0:20 11.9
 b 2012-1-1 2:20 9.6
 b 2012-1-1 4:20 12.6
 b 2012-1-1 6:20 11.9
 b 2012-1-1 8:20 9.6
 b 2012-1-1 10:20 12.6
 b 2012-1-1 12:20 11.9
 b 2012-1-1 14:20 9.6
 b 2012-1-1 16:20 9.6
 b 2012-1-1 18:20 12.6
 b 2012-1-1 20:20 11.9
 b 2012-1-1 22:20 9.6

把一天时间分成若干时间段,这里假设为6个,每4小时为一个时间段
 针对每个Doer的每天的操作,将各个时间段的num最小的记录对应的第一个时间填充到对应自段中,形成类似下面的表结构
doer 0-4               4-8            8-12...
 a    2012-1-1 0:09 2012-1-1 4:09 2012-1-1 8:09 ...
 b    2012-1-1 0:20 2012-1-1 4:20 2012-1-1 8:20 ... 
------最佳解决方案--------------------
select doer,convert(varchar(10),dotime,120) as rq 
         [0-4]=(select top 1 dotime from tb 
              where convert(varchar(10),dotime,120)=convert(varchar(10),a.dotime,120) 
              and datepart(hh,dotime) between 0 and 4 order by num),
         [4-8]=(select top 1 dotime from tb 
              where convert(varchar(10),dotime,120)=convert(varchar(10),a.dotime,120) 
              and datepart(hh,dotime) between 4 and 8 order by num),
            ..............
  from tb a group by doer,convert(varchar(10),dotime,120)  
------其他解决方案--------------------
----------------------------
-- Author  :TravyLee(物是人非事事休,欲语泪先流!)
-- Date    :2012-11-20 09:17:19
-- Version:
--      Microsoft