An update with multiple conditions. SQL 2008

怎甘沉沦 提交于 2019-12-10 12:23:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!