declare @tblIndexTmp as table(Datum datetime,MainIndex nvarchar(50),Stand float,Variable_1 float,UserName nvarchar(50))
insert into @tblIndexTmp values('1999-01-01', 'SX5E', 3342.32,null,'Kongta')
insert into @tblIndexTmp values('1999-01-04', 'SX5E', 3543.1 ,null,'Kongta')
insert into @tblIndexTmp values('1999-01-05', 'SX5E', 3604.67, null,'Kongta')
insert into @tblIndexTmp values('1999-01-06', 'SX5E', 3685.36, null,'Kongta')
insert into @tblIndexTmp values('1999-01-07', 'SX5E', 3627.87, null,'Kongta')
insert into @tblIndexTmp values('1999-01-08', 'SX5E', 3616.57, null,'Kongta')
insert into @tblIndexTmp values('1999-01-11', 'SX5E', 3546.4 , null,'Kongta')
declare @UserName nvarchar(50)
set @UserName = 'Kongta'
update t1
set t1.Variable_1 = t3.Variable_1
from @tblIndexTmp t1
join (select Datum,MainIndex,
(select avg(Stand) from @tblIndexTmp t1
where t1.Datum between dateadd(dd,-200,t2.Datum) and dateadd(dd,-1,t2.Datum)
and datepart(weekday,t1.Datum) not in (6,7)
and t1.UserName = @UserName) Variable_1
from @tblIndexTmp t2) t3
on t1.Datum = t3.Datum and t1.MainIndex = t3.MainIndex
where t1.UserName = @UserName
select * from @tblIndexTmp
/*
1999-01-01 00:00:00.000 SX5E 3342.32 NULL Kongta
1999-01-04 00:00:00.000 SX5E 3543.1 NULL Kongta
1999-01-05 00:00:00.000 SX5E 3604.67 3543.1 Kongta
1999-01-06 00:00:00.000 SX5E 3685.36 3573.885 Kongta
1999-01-07 00:00:00.000 SX5E 3627.87 3611.04333333333 Kongta
1999-01-08 00:00:00.000 SX5E 3616.57 3615.25 Kongta
1999-01-11 00:00:00.000 SX5E 3546.4 3615.25 Kongta
*/
|