I need to update some records here are the table structures
Table A is the main one we need to update some records
A(Id,DataYear0,DataYear1,DataYear3)
Table B has some other than data that we require
B(Id,Year,DataYear)
Example data for Table 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)
With 2012 as the current Year, I need to update the data values of the previous three years(i.e, 2011,2010,2009) in Table A
So, table A needs to be updated as A(abc,1.78,1.52,1.23) for the above example. Similarly other records need to be updated.
Id is the primary key on both tables.
The query I have so far is
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
This did not work, because I think it is returning extra year records apart from the years that we want i.e., just the last three years
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()))
But still the data is not being updated.
Tried using 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
The data is still not updated. I would appreciate any suggestions that anyone might have. Many thanks in advance.
You could do something like this: