Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Dynamic Update

$
0
0

Hi Everyone,

I need to update a table for 3 years and am using the below query which essentially is one update statement for each year. I am sure there must be a more efficient way to write this. Any help would be truly appreciated. Thanks!

UPDATE [dbo].[Employees]
SET Q1 = SubQuery.Q1,
	Q2 = SubQuery.Q2,
	Q3 = SubQuery.Q3,
	Q4 = SubQuery.Q4
FROM (SELECT  SUM(Q1) AS Q1, SUM(Q2) AS Q2, SUM(Q3) AS Q3, SUM(Q4) AS Q4 FROM [dbo].[Employees] WHERE ID IN (11, 12, 13) AND Year = YEAR(GETDATE())) SubQuery
WHERE ID = 13 AND Year = YEAR(GETDATE())

UPDATE [dbo].[Employees]
SET Q1 = SubQuery.Q1,
	Q2 = SubQuery.Q2,
	Q3 = SubQuery.Q3,
	Q4 = SubQuery.Q4
FROM (SELECT  SUM(Q1) AS Q1, SUM(Q2) AS Q2, SUM(Q3) AS Q3, SUM(Q4) AS Q4 FROM [dbo].[Employees] WHERE ID IN (11, 12, 13) AND Year = YEAR(GETDATE())-1) SubQuery
WHERE ID = 13 AND Year = YEAR(GETDATE())-1

UPDATE [dbo].[Employees]
SET Q1 = SubQuery.Q1,
	Q2 = SubQuery.Q2,
	Q3 = SubQuery.Q3,
	Q4 = SubQuery.Q4
FROM (SELECT  SUM(Q1) AS Q1, SUM(Q2) AS Q2, SUM(Q3) AS Q3, SUM(Q4) AS Q4 FROM [dbo].[Employees] WHERE ID IN (11, 12, 13) AND Year = YEAR(GETDATE())-1) SubQuery
WHERE ID = 13 AND Year = YEAR(GETDATE())-2


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>