日期:2014-05-18  浏览次数:20453 次

这种判断时间的SQL怎么写呢?
字段A 字段B 字段C 字段D 字段4
A 结束 3 a 2012/1/3
A 开始 2 b 2012/1/4
A 开始 1 c 2012/1/5
B 结束 7 a 2012/1/6
B 开始 6 b 2012/1/7
B 开始 5 c 2012/1/8
B 开始 4 d 2012/1/9
B 开始 3 e 2012/1/10
B 开始 2 f 2012/1/11
B 开始 1 g 2012/1/12
C 开始 2 a 2012/5/16
C 开始 1 b 2012/5/15
D 开始 3 a 2012/5/12
D 开始 2 b 2012/5/11
D 开始 1 c 2012/5/10
字段B是字段A的状态,
1、需要把不含结束的记录集提取出来,那么这个时候就是:
C 开始 2 a 2012/5/16
C 开始 1 b 2012/5/15
D 开始 3 a 2012/5/12
D 开始 2 b 2012/5/11
D 开始 1 c 2012/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



------解决方案--------------------
SQL code

--> 测试数据:[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
*/

------解决方案--------------------
探讨
SQL code


--> 测试数据:[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
)
inser……