so we will need to update the "updateto" field following way
for row 1) we compare AD and hub and since hub is null updateto = AD
row 2 ) we compare AD with hub and since AD is null updateto = hub
row 3 ) we compare AD and hub with hb . since AD matches hb updateto = AD
row 4 ) we compare AD and hub with hb and since they all three are same we compare addate with hubdate and since hubdate is higher updateto = hub
there are more then 4 rows in the table. I have just given an example over here.
how do i write a sql statement to make this happen.
--/*if object_id('tempdb..#temp') is not null drop table #tempcreate table #temp(updateto varchar(100), hb int, AD int, AddDate date, Hub int, HubDate date)insert into #temp(hb, AD, AddDate, Hub, HubDate)select * from (values (1, 5, '8/4/2016', null, null), (6, null, null, 8, '8/5/2016'), (7, 7, '8/1/2016', 5, '8/4/2016'), (11, 11, '8/3/2016', 11, '5/4/2016') ) a(hb, AD, AdDate, Hub, HubDate)--*/select * from #tempupdate #temp set updateto= case when hub is null then AD when AD is null then Hub when AD=Hub then AD when AD=Hub and Hub=hb and HubDate>AddDate then Hub else AD endselect * from #temp
Open in new window