2009-10-12 4 views
1

나는 PID의 내가 가장 낮은 득점 기록을 제거 할 존재하는 중복 다음 표 어떤 들어SQL 쿼리 중복 제거 도움말

ID  PID  SCORE 
1  1  50 
2  33  20 
3  1  90 
4  5  55 
5  7  11 
6  22  34 

에서 반 중복 레코드를 제거해야합니다. 위의 예에서 ID 1은 제거됩니다. 루프를 사용하지 않고이 작업을 수행하는 방법을 찾고 있지만 실제로 고민하고 있습니다.

도움을 주시면 감사하겠습니다. 더 중복이없는 결과를 떠나

감사

답변

1
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 
0
WITH q AS 
     (
     SELECT *, ROW_NUMBER() OVER (PARTITION BY pid ORDER BY score) AS rn 
     FROM mytable 
     ) 
DELETE 
FROM q 
WHERE rn = 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 
+3

점수가 어떻게 표시되지 않습니까? – Mark

+0

복제가없는 레코드도 삭제하지 않겠습니까? – Gavin

+0

pid로 분할하지 말고, 점수순으로 정렬하고 행 번호 = 2를 삭제해야합니까? – Preets

-1

나는 당신의 쿼리를 볼 수 없습니다, 그래서 나는이 예제를했습니다

SELECT 
    PID, 
    MAX(Score) 
FROM 
    tblTable 
GROUP BY 
    PID 
+0

OP가 다른 것을 삭제하지 않기를 원하는 것들을 선택합니다. – Mark

0

시도해보십시오.

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