我需要获得14天平均Col 1并更新同一表格的第2列。因此,如果你看看Col 2,我今天需要在10/29和11/15日期范围之间获得Col 1数据的平均百分比为18.2%。我对如何在更新语句中对这种函数进行分组感到困惑。任何人都有线索?
表1
╔════════════╦═════════════╦═════╦════════╦════════╗
║ Today ║ Date ║Hours║ Col 1 ║ Col 2 ║
╠════════════╬═════════════╬═════╬════════╬════════╣
║ 10/29/2014 ║ 11/15/2014 ║ 220 ║ ║ ║
║ 10/30/2014 ║ 11/15/2014 ║ 220 ║ ║ ║
║ 10/31/2014 ║ 11/15/2014 ║ 200 ║ ║ ║
║ 11/1/2014 ║ 11/15/2014 ║ 200 ║ ║ ║
║ 11/2/2014 ║ 11/15/2014 ║ 200 ║ 9.09% ║ ║
║ 11/3/2014 ║ 11/15/2014 ║ 200 ║ 9.09% ║ ║
║ 11/4/2014 ║ 11/15/2014 ║ 160 ║ 20.00% ║ ║
║ 11/5/2014 ║ 11/15/2014 ║ 160 ║ 20.00% ║ ║
║ 11/6/2014 ║ 11/15/2014 ║ 160 ║ 20.00% ║ ║
║ 11/7/2014 ║ 11/15/2014 ║ 160 ║ 20.00% ║ ║
║ 11/8/2014 ║ 11/15/2014 ║ 120 ║ 25.00% ║ ║
║ 11/9/2014 ║ 11/15/2014 ║ 120 ║ 25.00% ║ ║
║ 11/10/2014 ║ 11/15/2014 ║ 120 ║ 25.00% ║ ║
║ 11/11/2014 ║ 11/15/2014 ║ 120 ║ 25.00% ║ ║
║ 11/12/2014 ║ 11/15/2014 ║ 100 ║ 16.67% ║ ║
║ 11/13/2014 ║ 11/15/2014 ║ 100 ║ 16.67% ║ ║
║ 11/14/2014 ║ 11/15/2014 ║ 100 ║ 16.67% ║ ║
║ 11/15/2014 ║ 11/15/2014 ║ 100 ║ 16.67% ║ 18.92% ║
╚════════════╩═════════════╩═════╩════════╩════════╝
答案 0 :(得分:0)
建议将平均值存储为十进制而不是varchar,因为可以在表示层中添加%。
以下是需要计算,子字符串和强制转换的查询,因为平均列是varchar。
编辑: 删除子字符串逻辑,因为它们是浮点列,根据OP注释。
update myTable
set [col 2] = T.avgValue
from (
select avg( [col 1] ) as avgValue
from mytable
where datediff(day,[Today],'2014-11-15 00:00:00') <=14 ) T
where datediff(day,[Today],'2014-11-15 00:00:00') <=14
编辑:
由于需要对每个日期进行此操作,因此可以使用游标
完成declare @dateval datetime
declare tempcur cursor for
select today from mytable
open tempcur
fetch next from tempcur into @dateval
WHILE @@FETCH_STATUS = 0
begin
update myTable
set [col 2] = T.avgValue
from (
select avg( [col 1] ) as avgValue
from mytable
where datediff(day,myTable.[Today],@dateval) <=14
and today <= @dateval
) T
where today = @dateval
fetch next from tempcur into @dateval
end
close tempcur
deallocate tempcur