sql语句,同时满足多个条件的
求一个sql语句,同时满足多个条件的,在线等
就一个这样的简单的表
id starttime
1 2012-04-01 08:00:00
1 2012-04-01 15:20:00
1 2012-04-02 00:50:00
1 。。。
2 。。。
2 。。。
3 。。。
需求:我想查询一个 时间段内 每个id 发生 特定情况 的 次数
这个特定情况为:同一个id 在这个表中 当天的5:30:00到14:30:00有记录,并且在当天的14:30:01到第二天的14:30:00也有记录,那么就记一次。
最后要查询,在这个时间段内,每个id共发生几次这种情况
例如:上面的这个表中,1这个id在2012-04-01当天5:30:00到14:30:00有一条记录,在当天的14:30:01到第二天的14:30:00有两条记录,那么1这个id在2012-04-01到2012-04-02这个时间段内就有一次这个情况。
所以我就想要一个可以在任意一个时间段内(如2012-04-01到2012-04-20),查询每个id共发生这种情况几次的语句
结果: id 次数
1 2
。。 。。
------解决方案--------------------
就一个这样的简单的表
id starttime
1 2012-04-01 08:00:00
1 2012-04-01 15:20:00
1 2012-04-02 00:50:00
1 。。。
2 。。。
2 。。。
3 。。。
需求:我想查询一个 时间段内 每个id 发生 特定情况 的 次数
这个特定情况为:同一个id 在这个表中 当天的5:30:00到14:30:00有记录,并且在当天的14:30:01到第二天的14:30:00也有记录,那么就记一次。
最后要查询,在这个时间段内,每个id共发生几次这种情况
例如:上面的这个表中,1这个id在2012-04-01当天5:30:00到14:30:00有一条记录,在当天的14:30:01到第二天的14:30:00有两条记录,那么1这个id在2012-04-01到2012-04-02这个时间段内就有一次这个情况。
所以我就想要一个可以在任意一个时间段内(如2012-04-01到2012-04-20),查询每个id共发生这种情况几次的语句
结果: id 次数
1 2
。。 。。
------解决方案--------------------
- SQL code
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