问题
I have a table...
ProjectID UserID RoleID
101 1 10
101 2 10
102 2 10
102 3 10
103 1 10
Currently there is only one type of Role, role '10', but I'm wanting to add a new role, role '11', which will act as a lead. So any project that has a user with the role of '10', should have a lead. The user chosen to be lead will be based on a priorty list, in this example we'll say the order is 1, 2, 3.
Expected result...
ProjectID UserID RoleID
101 1 11
101 2 10
102 2 11
102 3 10
103 1 11
回答1:
You can figure out which user has the highest priority by using row_number(). SQL Server let's you do this in an updatable CTE, so the query looks like this:
with toupdate as (
select t.*,
row_number() over (partition by projectid
order by (case when userid = 1 then 1
when userid = 2 then 2
when userid = 3 then 3
else 4
end
)
) as PriorityForLead
from table t
)
update toupdate
set RoleId = 11
where PriorityForLead = 1;
来源:https://stackoverflow.com/questions/25626401/an-update-with-multiple-conditions-sql-2008