Welcome to itblog

Every Day In Every Way I Am Getting Better And Better~

怎样在一个时间段内记录,只取最早的一条记录?

表:

工号        日期
--------------------------------
12006-03-15 08:00:40.000
12006-03-15 18:10:35.000
12006-03-15 18:10:36.000
22006-03-15 07:54:45.000
22006-03-15 18:10:03.000
32006-03-15 07:59:46.000
32006-03-15 07:59:47.000
32006-03-15 19:15:30.000
42006-03-15 08:03:47.000
42006-03-15 19:41:08.000
52006-03-15 19:41:09.000

结果(同一工号日期在5分钟范围内的记录,只取最早的一条记录):
工号        日期
---------------------------------
12006-03-15 08:00:40.000
12006-03-15 18:10:35.000
22006-03-15 07:54:45.000
22006-03-15 18:10:03.000
32006-03-15 07:59:46.000
32006-03-15 19:15:30.000
42006-03-15 08:03:47.000
42006-03-15 19:41:08.000
52006-03-15 19:41:09.000

declare @tbl table (工号 int,日期 datetime)
insert into @tbl
select 1,'2006-03-15 08:00:40.000'
union select 1,'2006-03-15 18:10:35.000'
union select 1,'2006-03-15 18:10:36.000'
union select 2,'2006-03-15 07:54:45.000'
union select 2,'2006-03-15 18:10:03.000'
union select 3,'2006-03-15 07:59:46.000'
union select 3,'2006-03-15 07:59:47.000'
union select 3,'2006-03-15 19:15:30.000'
union select 4,'2006-03-15 08:03:47.000'
union select 4,'2006-03-15 19:41:08.000'
union select 5,'2006-03-15 19:41:09.000'

select * from @tbl as a
where not exists(
  select * from @tbl where 工号=a.工号 and
     abs(datediff(Second,日期,a.日期))<=300 and a.日期<日期)

declare @tbl table (工号 int,日期 datetime)
insert into @tbl
      select 1,'2006-03-15 08:00:40.000'
union select 1,'2006-03-15 18:10:35.000'
union select 1,'2006-03-15 18:10:36.000'
union select 2,'2006-03-15 07:54:45.000'
union select 2,'2006-03-15 18:10:03.000'
union select 3,'2006-03-15 07:59:46.000'
union select 3,'2006-03-15 07:59:47.000'
union select 3,'2006-03-15 19:15:30.000'
union select 4,'2006-03-15 08:03:47.000'
union select 4,'2006-03-15 19:41:08.000'
union select 5,'2006-03-15 19:41:09.000'

select distinct a.*
from
    @tbl a
where
    not exists(select
                   1
               from
                   @tbl
               where
                   工号=a.工号
                   and
                   (datediff(ss,日期,a.日期) between 1 and 300))

 

 

阅读更多
文章标签: insert table
个人分类: SQL Sever
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

怎样在一个时间段内记录,只取最早的一条记录?

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭