日期:2014-05-17 浏览次数:20439 次
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2013-11-21 17:25:02
-- Verstion:
-- Microsoft SQL Server 2012 - 11.0.2100.60 (X64)
-- Feb 10 2012 19:39:15
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([vehPlate] int,[enCardID] varchar(3),[EnTime] varchar(16))
insert [tb]
select 111111,'c1','2013-11-21 17:11' union all
select 111111,'c1','2013-11-21 17:15' union all
select 111111,'c2','2013-11-21 17:15' union all
select 222222,'c3','2013-11-21 17:13' union all
select 222222,'c4','2013-11-22 17:13' union all
select 222222,'c5','2013-11-21 17:09' union all
select 333333,'c9','2013-11-22 17:08' union all
select 444444,'c10','2013-11-22 17:09'
--------------开始查询--------------------------
SELECT
*
FROM
TB a
WHERE
EXISTS(SELECT 1 FROM TB WHERE vehPlate=a.vehPlate AND enCardID<>a.enCardID AND DATEDIFF(mi,EnTime,a.EnTime)<=10)
AND
NOT EXISTS(SELECT 1 FROM TB WHERE vehPlate=a.vehPlate AND enCardID=a.enCardID AND EnTime<a.EnTime)
----------------结果----------------------------
/* vehPlate enCardID EnTime
----------- -------- ----------------
111111 c1 2013-11-21 17:11
111111 c2 2013-11-21 17:15
222222 c3 2013-11-21 17:13
222222 c5 2013-11-21 17:09
(4 行受影响)
*/
-- 建测试表
create table ENList
(VehPlate varchar(10),EnCardID varchar(10),EnTime varchar(20))
insert into ENList
select&nb