代码之家  ›  专栏  ›  技术社区  ›  NoBullMan

替换和删除SQL Server数据库中的列值

  •  1
  • NoBullMan  · 技术社区  · 8 年前

    我有一个包含用户id和课程id的表。决定有些课程实际上是重复的,我需要去掉它们。因此,这意味着我必须用另一个课程ID替换其中一个,但要确保没有重复的课程ID。

    下面是一个示例:

    UserID    CourseID
    ------    --------
    1         1
    1         2
    1         3
    1         4
    2         1
    2         2
    

    他们决定课程ID 1和3是相同的,因此需要去掉1,替换为3,最后得到:

    UserID    CourseID
    ------    --------
    1         2
    1         3
    1         4
    2         3
    2         2
    

    因此,对于用户ID 2来说,它只是一个更新,当然是ID,但是对于用户ID 1来说,它是一个更新和删除。此表中有课程id的唯一约束,因此无法将所有1更新为3并删除重复项。

    2 回复  |  直到 8 年前
        1
  •  1
  •   simon at rcl    8 年前

    首先删除那些会产生重复的内容:

    delete uc1
    from UserCourse uc1
    inner join UserCourse uc3 on uc3.UserId = uc1.UserId
    where uc1.CourseId = 1 and uc3.CourseId = 3
    

    然后,只需进行更新:

    update UserCourse set CourseId = 3 where CourseId = 1
    
        2
  •  0
  •   S3S    8 年前

    我会分两个阶段来做。。。第一次更新。

    update table 
    set CourseID = 3 
    where CourseID = 1
    

    然后删除重复项

    with cte as (
    select *, row_number() over (partition by UserID, CourseID order by CourseID) RN
    )
    
    
    select * from cte where RN <> 1
    --the below command will delete what is returned from the select
    --delete from cte 
    --where RN <> 1