日期:2014-05-18 浏览次数:20439 次
IF OBJECT_ID('tb') IS NOT NULL DROP TABLE tb; GO CREATE TABLE tb(id int, mid int, starttime datetime); INSERT INTO tb(id, starttime) select 1, '2012-04-01 08:00:00' union all select 1, '2012-04-01 15:20:00' union all select 1, '2012-04-02 00:50:00' union all select 1, '2012-04-02 8:50:00' union all select 1, '2012-04-02 18:50:00' union all select 1, '2012-04-03 5:50:00' union all select 2, '2012-04-04 5:50:00' union all select 2, '2012-04-04 8:50:00' union all select 2, '2012-04-04 15:50:00'; --select id, starttime from tb; select a.id, sum([count]) as 次数 from ( select id, max(num) as [Count] from ( select a.id, a.starttime, 1 as num from tb a where a.starttime >= '2012-04-01' and a.starttime <= '2012-04-12' and convert(varchar(8), a.starttime, 108) between '05:30:00' and '14:30:00' and (exists ( select 1 from tb b where a.id = b.id and b.starttime between cast( convert(varchar(10), a.starttime, 120) + ' 05:30:00' as datetime) and cast( convert(varchar(10), a.starttime, 120) + ' 14:30:00' as datetime) ) ) and (exists ( select 1 from tb b1 where a.id = b1.id and b1.starttime > cast( convert(varchar(10), a.starttime, 120) + ' 14:30:00' as datetime) and b1.starttime <= cast( convert(varchar(10), a.starttime + 1, 120) + ' 14:30:00' as datetime) ) ) ) t group by id, convert(varchar(10), starttime, 120) ) a group by a.id