Hi,
I have a requirements to get the nearest date. I have 2 table t1 and t2. i need to use the date from t1 to get the nearest date from t2 table. I makea query but could not get the exact result. any help is very much appreciated. thank you.
please see below sample data and query
Create table #t1
(cs_no nvarchar(35), model nvarchar(35), audit_date datetime)
insert into #t1 (cs_no,model, audit_date)values('9000000000019761824','TOPR3000430PPH664SIL','2015-01-03 19:23:54.980')
insert into #t1 (cs_no,model, audit_date)values('990002595125962','COR3003110VS980','2015-05-09 14:56:41.447')
insert into #t1 (cs_no,model, audit_date)values('990002595125962',' COR3003110VS980','2015-06-29 12:09:17.160')
Create table #t2
(cs_no nvarchar(35), es_num nvarchar(35), prodid nvarchar(35), audit_date datetime, ctype varchar(36))
insert into #t2(cs_no, es_num , prodid , audit_date, ctype) values('9000000000019761824','354403060637509','PRC005271772','2015-03-20 16:43:07.000','PROD')
insert into #t2(cs_no, es_num , prodid , audit_date, ctype) values('9000000000019761824','354403060637509','PRC005065526','2015-02-07 09:50:08.000','PROD')
insert into #t2(cs_no, es_num , prodid , audit_date, ctype) values('990002595125962','990002595125962','PRC005294334','2015-03-26 16:54:22.000','PROD')
insert into #t2(cs_no, es_num , prodid , audit_date, ctype) values('990002595125962','990002595125962','PRC005506808','2015-05-17 00:59:55.000','PROD')
insert into #t2(cs_no, es_num , prodid , audit_date, ctype) values('990002595125962','990002595125962','PRC004948361','2015-01-19 04:34:56.000','PROD')
insert into #t2(cs_no, es_num , prodid , audit_date, ctype) values('990002595125962','990002595125962','PRC005786594','2015-07-08 21:29:35.000','PROD')
select a.*,x.audit_date, x.prodid, x.ctype
from #t1 a
outer apply
(select top 1 audit_date, prodid, ctype from #t2 b where b.audit_date >=a.audit_date and b.cs_no=a.cs_no )x
cs_no================model=================audit_date===============audit_date==============prodid=======ctype
9000000000019761824--TOPR3000430PPH664SIL--2015-01-03 19:23:54.980--2015-02-07 09:50:08.000--PRC005065526--PROD
990002595125962------COR3003110VS980-------2015-05-09 14:56:41.447--2015-05-17 00:59:55.000--PRC005506808--PROD
990002595125962------COR3003110VS980-------2015-06-29 12:09:17.160--2015-07-08 21:29:35.000--PRC005786594--PROD