ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • SQL 중복확인 & 중복제거 조회 & 중복제거
    SQL 2023. 1. 26. 14:28
    반응형

    개요

    개발하다보니 중복을 확인하고 제거할 일이 있어 기록

    중복확인

    SELECT
        COL_1,
        COL_2,
        COUNT(*)
    FROM TABLE
    GROUP BY COL_1, COL_2;
    --HAVING COUNT(*) > 1;

    중복제거 조회

    SELECT DISTINCT
        COL_1,
        COL_2
    FROM TABLE;

    중복제거

    DELETE TABLE
    WHERE PK IN (
        SELECT 
        	A.PK 
        FROM TABLE A INNER JOIN
            (
                SELECT 
                	MAX(PK) AS PK, 
                    COL_1, 
                    COL_2, 
                    COUNT(*) 
                FROM TABLE
                GROUP BY COL_1, COL_2
                HAVING COUNT(*) > 1
            ) B 
            ON A.COL_1 = B.COL_2
                AND A.COL_1 = B.COL_2
                AND A.PK != B.PK
    );

     

    https://jasmintime.com/191

    반응형
Designed by Tistory.