我有一张桌子......
ProjectID UserID RoleID
101 1 10
101 2 10
102 2 10
102 3 10
103 1 10
目前只有一种类型的角色,角色' 10'但我想要添加一个新角色,角色' 11'这将充当铅。因此,任何具有' 10'角色的用户的项目都应该具有领先优势。被选为领导者的用户将基于一个优先列表,在这个例子中,我们说订单是1,2,3。
预期结果......
ProjectID UserID RoleID
101 1 11
101 2 10
102 2 11
102 3 10
103 1 11
答案 0 :(得分:1)
您可以使用row_number()
确定哪个用户具有最高优先级。 SQL Server允许您在可更新的CTE中执行此操作,因此查询如下所示:
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;