SQL查询重复删除帮助
我需要从下表中删除半重复记录SQL查询重复删除帮助,sql,sql-server,duplicate-removal,Sql,Sql Server,Duplicate Removal,我需要从下表中删除半重复记录 ID PID SCORE 1 1 50 2 33 20 3 1 90 4 5 55 5 7 11 6 22 34 对于存在的任何重复PID,我希望删除最低评分记录。在上面的示例中,ID 1将被删除。我试图想出一种不使用循环的方法,但我真的很挣扎 任何帮助都将不胜感激 谢谢 要保留不重复的结果,请
ID PID SCORE
1 1 50
2 33 20
3 1 90
4 5 55
5 7 11
6 22 34
对于存在的任何重复PID,我希望删除最低评分记录。在上面的示例中,ID 1将被删除。我试图想出一种不使用循环的方法,但我真的很挣扎
任何帮助都将不胜感激
谢谢
要保留不重复的结果,请执行以下操作:
WITH q AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY pid ORDER BY score) AS rn,
COUNT(*) OVER (PARTITION BY pid) AS cnt
FROM mytable
)
DELETE
FROM q
WHERE rn = 1
AND cnt > 1
我看不到你的查询,所以我编了这个例子
SELECT
PID,
MAX(Score)
FROM
tblTable
GROUP BY
PID
试试这个
declare @tt table(id int, pid int,score int)
insert into @tt
select 1,1,50 union all
select 2,33,50 union all
select 8,33,80 union all
select 3,1,90 union all
select 4,5,50 union all
select 5,5,10 union all
select 6,6,10 union all
select 7,6,50
---------
delete from @tt where id in (
select t1.id from @tt t1 inner join
(
select MIN(score) tScore,pid tPid from @tt where pid in
(select pid from @tt group by pid having count (pid) > 1) group by pid
) t2 on t1.pid=t2.tPid and t1.score=t2.tScore)
select * from @tt
这不会也会删除没有重复项的记录吗?您不应该按pid分区、按分数排序并删除行数为2的记录吗?@op只想删除最低的分数id,而不是所有其他的。@Mark:当然,我没有注意到@op想删除最低的分数,而不是最低的id。这会选择op不想删除其他的分数
DELETE t.*
FROM Table1 t
JOIN (SELECT pid, MIN(score) minScore, MAX(id) maxId
FROM Table1
GROUP BY pid) t1
ON t.pid = t1.pid
AND t.score = t1.minScore
AND t.id < t1.maxId
declare @tt table(id int, pid int,score int)
insert into @tt
select 1,1,50 union all
select 2,33,50 union all
select 8,33,80 union all
select 3,1,90 union all
select 4,5,50 union all
select 5,5,10 union all
select 6,6,10 union all
select 7,6,50
---------
delete from @tt where id in (
select t1.id from @tt t1 inner join
(
select MIN(score) tScore,pid tPid from @tt where pid in
(select pid from @tt group by pid having count (pid) > 1) group by pid
) t2 on t1.pid=t2.tPid and t1.score=t2.tScore)
select * from @tt