I have a table that looks something like this:
SetId ID Premium 2012 5 Y 2012 6 Y 2013 5 N 2013 6 N
I want to update the 2013 records with the premium values where the setid equals 2012.
So after the query it would look like this:
SetId ID Premium 2012 5 Y 2012 6 Y 2013 5 Y 2013 6 Y
Any help greatly appreciated
In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.
UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.
UPDATE t SET t.Premium = (SELECT TOP 1 t2.Premium FROM dbo.TableName t2 WHERE t2.SetId = 2012) FROM dbo.TableName t WHERE t.SetId = 2013
Demonstration
It's not clear which 2012 value you want to use to update which 2013 value, i've assumed that the ID
should be the same.
Full example using table variables that you can test yourself in management studio.
DECLARE @Tbl TABLE ( SetId INT, Id INT, Premium VARCHAR(1) ) INSERT INTO @Tbl VALUES (2012, 5, 'Y') INSERT INTO @Tbl VALUES (2012, 6, 'Y') INSERT INTO @Tbl VALUES (2013, 5, 'N') INSERT INTO @Tbl VALUES (2013, 6, 'N') --Before Update SELECT * FROM @Tbl --Something like this is what you need UPDATE t SET t.Premium = t2.Premium FROM @Tbl t INNER JOIN @Tbl t2 ON t.Id = t2.Id WHERE t2.SetId = 2012 AND t.SetId = 2013 --After Update SELECT * FROM @Tbl
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With