[COLOR=green]-- build test data[/color]
create table #t (product char(10), date datetime, points int, flag char(1))
insert into #t values ('A', '1/15/07', 15, '0')
insert into #t values ('A', '1/16/07', 16, '0')
insert into #t values ('A', '1/17/07', 17, '0')
insert into #t values ('A', '1/18/07', 18, '0')
insert into #t values ('B', '1/15/07', 15, '0')
insert into #t values ('B', '1/16/07', 15, '0')
insert into #t values ('B', '1/17/07', 15, '0')
insert into #t values ('B', '1/18/07', 15, '0')
insert into #t values ('C', '1/15/07', 15, '0')
insert into #t values ('C', '1/16/07', 15, '0')
insert into #t values ('C', '1/17/07', 15, '0')
insert into #t values ('C', '1/18/07', 16, '0')
[COLOR=green]-- last date:[/color]
CREATE TABLE #LatestDate (product char(10), date datetime, discriminant char(18))
INSERT INTO #LatestDate
SELECT PRODUCT,MAX(DATE),convert(char(8),max(date),112) + product
FROM #T GROUP BY PRODUCT
[COLOR=green]-- next-to-last date:[/color]
CREATE TABLE #NextToLatestDate (product char(10), date datetime, discriminant char(10))
INSERT INTO #NextToLatestDate
SELECT t1.product,max(t1.date),convert(char(8),max(t1.date),112) + t1.product
FROM #T t1
JOIN #LatestDate t0 on t0.product=t1.product
where (convert(char(8),(t1.date),112) + t1.product) <> discriminant
group by t1.product
[COLOR=green]-- what to update:[/color]
create table #UpdateControl (discriminant char(10))
insert into #UpdateControl
select convert(char(8),(t1.date),112) + t1.product
from #LatestDate ld
join #t t1 on t1.product=ld.product and t1.date=ld.date
join #NextToLatestDate nt on nt.product=ld.product
join #t t2 on t2.product=nt.product and t2.date=nt.date
where (t1.points <> t2.points) and (t1.flag = '0' or t2.flag = '0')
insert into #UpdateControl
select convert(char(8),(t2.date),112) + t2.product
from #LatestDate ld
join #t t1 on t1.product=ld.product and t1.date=ld.date
join #NextToLatestDate nt on nt.product=ld.product
join #t t2 on t2.product=nt.product and t2.date=nt.date
where (t1.points <> t2.points) and (t1.flag = '0' or t2.flag = '0')
[COLOR=green]-- do updates[/color]
update #t set flag='1'
where ((convert(char(8),(#t.date),112) + #t.product)) in
(select discriminant from #UpdateControl)
[COLOR=green]-- check results[/color]
select * from #t
[COLOR=green]-- cleanup[/color]
drop table #UpdateControl
drop table #NextToLatestDate
drop table #LatestDate
[COLOR=green]-- remove test data[/color]
drop table #t