日期:2014-05-18 浏览次数:20499 次
--> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]( [字段A] varchar(1), [字段B] varchar(4), [字段C] int, [字段D] varchar(1), [字段4] datetime ) insert [test] select 'A','结束',3,'a','2012/1/3' union all select 'A','开始',2,'b','2012/1/4' union all select 'A','开始',1,'c','2012/1/5' union all select 'B','结束',7,'a','2012/1/6' union all select 'B','开始',6,'b','2012/1/7' union all select 'B','开始',5,'c','2012/1/8' union all select 'B','开始',4,'d','2012/1/9' union all select 'B','开始',3,'e','2012/1/10' union all select 'B','开始',2,'f','2012/1/11' union all select 'B','开始',1,'g','2012/1/12' union all select 'C','开始',2,'a','2012/5/16' union all select 'C','开始',1,'b','2012/5/15' union all select 'D','开始',3,'a','2012/5/12' union all select 'D','开始',2,'b','2012/5/11' union all select 'D','开始',1,'c','2012/5/10' ;with t as( select * from test a where not exists(select 1 from test b where a.字段A=b.字段A and b.[字段B]='结束') ) select distinct [字段A],[字段B], (select max([字段C]) from t b where a.字段A=b.字段A) as [字段C], (select [字段D] from t c where [字段C]= (select MIN([字段C]) from t d where c.字段A=d.字段A) and c.字段A=a.字段A) as [字段D], (select convert(varchar(10),[字段4],120) from t c where [字段C]= (select MIN([字段C]) from t d where c.字段A=d.字段A) and c.字段A=a.字段A) as [字段4] from t a where DATEDIFF(dd, (select convert(varchar(10),[字段4],120) from t c where [字段C]= (select MIN([字段C]) from t d where c.字段A=d.字段A) and c.字段A=a.字段A),GETDATE())>3 /* 字段A 字段B 字段C 字段D 字段4 D 开始 3 c 2012-05-10 */
------解决方案--------------------