I am working on a table on SQL where I need to fill in a new column depending on the value of 2 other columns in the table.
The rules are: - New column = 1 if Row id = 1 and the group id for that row has more rows with the same group id (See pic) - New column = 2 if Row id >= 2 - Anything else will make the new column 0
This is my query to update the new column which works:
UPDATE t1 SET t1.New_Column = CASE WHEN t1.RowID >= 2 THEN 2
ELSE CASE WHEN t1.RowID = 1 and (SELECT count(*) FROM dbo.__test1 as t2 WHERE t2.GroupID = t1.GroupID) > 1
THEN 1 ELSE 0 END END from dbo.__test1 as t1
The end table result(Correct):
I want to know if there is a better and more efficient way of updating the new column as I feel calling the table within the select to count the number of group id's doesn't seem right?
Thanks