这种判断时间的SQL怎么写呢?
字段A字段B字段C字段D字段4
A结束3a2012/1/3
A开始2b2012/1/4
A开始1c2012/1/5
B结束7a2012/1/6
B开始6b2012/1/7
B开始5c2012/1/8
B开始4d2012/1/9
B开始3e2012/1/10
B开始2f2012/1/11
B开始1g2012/1/12
C开始2a2012/5/16
C开始1b2012/5/15
D开始3a2012/5/12
D开始2b2012/5/11
D开始1c2012/5/10
字段B是字段A的状态,
1、需要把不含结束的记录集提取出来,那么这个时候就是:
C开始2a2012/5/16
C开始1b2012/5/15
D开始3a2012/5/12
D开始2b2012/5/11
D开始1c2012/5/10
2、并且取得最大的那个字段C的值和最小的哪一个对应的字段D的值,这个时候就是:
C 开始 2 b 2012/5/15
D 开始 3 c 2012/5/10
3,需要把字段4中的时间取出来和服务器时间做相减,只需要日期差额大于三天的记录。
所以,最终结果就是:
D 开始 3 c 2012/5/10
[解决办法]
--> 测试数据:[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 allselect 'A','开始',2,'b','2012/1/4' union allselect 'A','开始',1,'c','2012/1/5' union allselect 'B','结束',7,'a','2012/1/6' union allselect 'B','开始',6,'b','2012/1/7' union allselect 'B','开始',5,'c','2012/1/8' union allselect 'B','开始',4,'d','2012/1/9' union allselect 'B','开始',3,'e','2012/1/10' union allselect 'B','开始',2,'f','2012/1/11' union allselect 'B','开始',1,'g','2012/1/12' union allselect 'C','开始',2,'a','2012/5/16' union allselect 'C','开始',1,'b','2012/5/15' union allselect 'D','开始',3,'a','2012/5/12' union allselect 'D','开始',2,'b','2012/5/11' union allselect 'D','开始',1,'c','2012/5/10';with tas(select * from test awhere 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 awhere 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 字段4D 开始 3 c 2012-05-10*/
[解决办法]