如何在SQL 2000中删除重复行?

Mik*_*ook 1 sql sql-server-2000

我以为我弄明白了,但事实证明我只是删除了第一张唱片.以下内容返回重复的行.所有都有2.我只想删除每个重复记录的第一个.

select scorestudentid, scoreadvisor, scorecorrect, count(*) 
from scores
where scoretestid = 3284
group by scorestudentid, scoreadvisor, scorecorrect
having count(scorestudentid) > 1
Run Code Online (Sandbox Code Playgroud)

哪个回报:

scorestudentid  scoreadvisor  scorecorrect  no column name
13033719        28059     3.0           2
13033777        28086     3.0           2
13033826        28147     3.0           2
13033960        28023     3.0           2
Run Code Online (Sandbox Code Playgroud)

所以我把它放在一起认为它会起作用:

set rowcount 1
delete
from scores
where scoretestid = 3284 
and scorestudentid in (
    select scorestudentid
    from scores
    where scoretestid = 3284
    group by scorestudentid
    having count(scorestudentid) > 1)
Run Code Online (Sandbox Code Playgroud)

它看起来应该是一个简单的概念,但我没有得到它.

基于托马斯脚本我更新了查询以适应但它仍然无法正常工作.

Delete Scores
Where Exists    (
                Select 1
                From Scores As S2
                Where S2.ScoreStudentId = Scores.ScoreStudentId
                        And S2.ScoreAdvisor = Scores.ScoreAdvisor
                        And S2.ScoreCorrect = Scores.ScoreCorrect
                Group By S2.ScoreStudentId, S2.ScoreAdvisor, S2.ScoreCorrect
                Having Count(*) > 1
                    And Min(S2.NewScoreID) = Scores.NewScoreID
                )
    And Scores.ScoreTestId = 3284
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 5

诀窍是使用主键列(你有一个,正确?),只需找到符合你想要的标准的第一个PK值.如果由于某些疯狂的原因您没有主键列,则添加一个Identity列并将其作为主键,然后执行删除操作.

编辑修改,使其更通用.如果您删除ScoreTest上的最终过滤器,它将根据ScoreStudentId,ScoreAdvisor和ScoreCorrect删除所有重复项.

Delete Scores
Where Exists    (
                Select 1
                From Scores As S2
                Where S2.ScoreStudentId = Scores.ScoresStudentId
                        And S2.ScoreAdvisor = Scores.ScoreAdvisor
                        And S2.ScoreCorrect = Scores.ScoreCorrect
                Group By S2.ScoreStudentId, S2.ScoreAdvisor, S2.ScoreCorrect
                Having Count(*) > 1
                    And Min(S2.PrimaryKeyColumn) = Scores.PrimaryKeyColumn
                )
    And Scores.ScoreTest = 3284
Run Code Online (Sandbox Code Playgroud)