你在這裏。我會讓你清理它並進行優化。其中一個子查詢可以進入視圖並且可以清除混亂的日期比較。如果您使用的是SQL 2008 R2,那麼請使用CAST作爲DATE。
declare @tbl1 table(
id int, Trackingid int, Status varchar(50), StatusDate datetime
)
declare @tbl2 table(
id int, Trackingid int, Status varchar(50), StatusDate datetime
)
----Source data
insert into @tbl1 (id, trackingid, status, statusdate) values(1,1,'PickedUp','10/01/10 1:00') --
insert into @tbl1 (id, trackingid, status, statusdate) values(2,1,'InTransit','10/02/10 1:00') --
insert into @tbl1 (id, trackingid, status, statusdate) values(8,1,'InTransit','10/02/10 3:00')
insert into @tbl1 (id, trackingid, status, statusdate) values(4,1,'Delayed','10/03/10 1:00')
insert into @tbl1 (id, trackingid, status, statusdate) values(5,1,'InTransit','10/03/10 1:01')
insert into @tbl1 (id, trackingid, status, statusdate) values(6,1,'AtDest','10/03/10 2:00')
insert into @tbl1 (id, trackingid, status, statusdate) values(7,1,'Deliv','10/03/10 3:00') --
insert into @tbl1 (id, trackingid, status, statusdate) values(3,2,'InTransit','10/03/10 1:00')
insert into @tbl1 (id, trackingid, status, statusdate) values(9,2,'AtDest','10/04/10 1:00')
insert into @tbl1 (id, trackingid, status, statusdate) values(10,2,'Deliv','10/04/10 1:05')
insert into @tbl1 (id, trackingid, status, statusdate) values(11,1,'Delayed','10/02/10 2:05')
----Target data
insert into @tbl2 (id, trackingid, status, statusdate) values(1,1,'PickedUp','10/01/10 1:00')
insert into @tbl2 (id, trackingid, status, statusdate) values(2,1,'InTransit','10/02/10 1:00')
insert into @tbl2 (id, trackingid, status, statusdate) values(3,1,'Deliv','10/03/10 3:00')
select d.* from
(
select
* ,
ROW_NUMBER() OVER(PARTITION BY trackingid, CAST((STR(YEAR(statusdate)) + '/' +STR(MONTH(statusdate)) + '/' +STR(DAY(statusdate))) AS DATETIME) ORDER BY statusdate) AS 'RN'
from @tbl1
) d
where
not exists
(
select RN from
(
select
* ,
ROW_NUMBER() OVER(PARTITION BY trackingid, CAST((STR(YEAR(statusdate)) + '/' +STR(MONTH(statusdate)) + '/' +STR(DAY(statusdate))) AS DATETIME) ORDER BY statusdate) AS 'RN'
from @tbl1
)f where f.RN = d.RN + 1 and d.status = f.status and f.trackingid = d.trackingid and
CAST((STR(YEAR(f.statusdate)) + '/' +STR(MONTH(f.statusdate)) + '/' +STR(DAY(f.statusdate))) AS DATETIME) =
CAST((STR(YEAR(d.statusdate)) + '/' +STR(MONTH(d.statusdate)) + '/' +STR(DAY(d.statusdate))) AS DATETIME)
)
and
not exists
(
select 1 from @tbl2 t2
where (t2.trackingid = d.trackingid
and t2.statusdate = d.statusdate
and t2.status = d.status)
)
and (
not exists
(
select 1 from
(
select top 1 * from @tbl2 t2
where t2.trackingid = d.trackingid
order by t2.statusdate desc
) g
where g.status = d.status
)
or not exists
(
select 1 from
(
select top 1 * from @tbl2 t2
where t2.trackingid = d.trackingid
and t2.statusdate <= d.statusdate
order by t2.statusdate desc
) g
where g.status = d.status
)
)
order by trackingid,statusdate
這實現了我所需要的一切,非常感謝! – joshlrogers 2010-10-05 17:44:50