我需要更新一些记录这里是表结构
表 A 是我们需要更新一些记录的主要表 A(Id,DataYear0,DataYear1,DataYear3)
表 B 有一些我们需要 B(Id,Year,DataYear) 以外的数据
表 B 的示例数据: B(abc,1950,1.25) B(abc,1951,1.29) .. .. B(abc,2008,1.67) B(abc,2009,1.23) B(abc,2010,1.52) B(abc,2011,1.78) B(abc,2012,NULL)
以2012为当前年份,我需要更新表A中前三年(即2011、2010、2009)的数据值
因此,对于上述示例,表 A 需要更新为 A(abc,1.78,1.52,1.23)。同样,其他记录也需要更新。
Id 是两个表的主键。
到目前为止我的查询是
UPDATE A SET
DataYear0 = CASE WHEN Year+1 = YEAR(GETDATE()) THEN DataYear END,
DataYear1 = CASE WHEN Year+2 = YEAR(GETDATE()) THEN DataYear END,
DataYear2 = CASE WHEN Year+3 = YEAR(GETDATE()) THEN DataYear END
FROM A
LEFT JOIN B
ON A.Id=B.Id
这没有用,因为我认为除了我们想要的年份之外,它还会返回额外的年份记录,即过去三年
UPDATE A SET
DataYear0 = CASE WHEN Year+1 = YEAR(GETDATE()) THEN DataYear END,
DataYear1 = CASE WHEN Year+2 = YEAR(GETDATE()) THEN DataYear END,
DataYear2 = CASE WHEN Year+3 = YEAR(GETDATE()) THEN DataYear END
FROM A
LEFT JOIN B
ON A.Id=B.Id
GROUP BY Id,Year,DataYear
HAVING ((YEAR(GETDATE())-3) <= Year) AND (Year <> YEAR(GETDATE()))
但仍然没有更新数据。
尝试使用 CTE
;WITH cte AS
(
SELECT
A.Id
,B.Year
,B.DataYear
,ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Year DESC) as row
FROM A
LEFT JOIN B
ON A.Id=B.Id
GROUP BY Id,Year,DataYear
HAVING ((YEAR(GETDATE())-3) <= Year) AND (Year <> YEAR(GETDATE()))
)
UPDATE
A.DataYear0 = CASE WHEN row=1 THEN DataYear END
,A.DataYear1 = CASE WHEN row=2 THEN DataYear END
,A.DataYear2 = CASE WHEN row=3 THEN DataYear END
FROM A
LEFT JOIN cte
ON A.Id = cte.Id
数据仍然没有更新。我将不胜感激任何人可能有的任何建议。提前谢谢了。