nYear GrpMeanTally y1
1910 4.1 1915
1911 7.2 1915
1912 4.6 1915
1913 5.6 1915
1914 2.3 1915
1915 1.7 1915
1916 4.2 1915
1917 5.2 1915
1918 6.0 1915
1919 1.9 1915
如何将每个nYear的值y1填充y1列作为前5年的GrpMeanTally值。即每年的y1 = nYear-5的GrpMeanTally
nyear = 1918的预期出局将是年龄= 1918 - 5 = 1913年的GrpMeanTally,即y1 = 5.6
答案 0 :(得分:0)
如果你在sql server 2012上试试这个:
;WITH t2 as
(select nyear, LAG(GrpMeanTally,5) OVER (ORDER by nyear) lagvalue FROM t)
UPDATE t1 SET y1=t2.lagvalue
FROM t t1
JOIN t2 ON t2.nyear=t1.nyear
2008年:
;WITH t2 as
(select nyear, GrpMeanTally, ROW_NUMBER() OVER (ORDER by nyear) rowno FROM t),
t3 AS
(SELECT ta.nyear, tb.GrpMeanTally lagvalue FROM t2 ta JOIN t2 tb ON ta.rowno-5=tb.rowno)
UPDATE t1 SET y1=t3.lagvalue
FROM t t1
JOIN t3 ON t3.nyear=t1.nyear