从与其他2个表连接的表中删除重复行

时间:2013-01-16 11:34:55

标签: sql-server-2008-r2

我有3个名为ICD10,Claims和AuthHeader的表。这三个表都连接在一起,创建了一个用于转到我的SSAS Cube的视图表。在ICD10中有重复的行,需要删除。如何在不弄乱与ICD10表连接的主键的情况下删除重复项?我看过这个剧本,但我不认为这是我需要的

DECLARE @table TABLE (
      id INT IDENTITY(1, 1)
    , data VARCHAR(20)
    )

DELETE  FROM @table

FROM    @table o

        INNER JOIN ( SELECT data
                     FROM   @table
                     GROUP BY data
                     HAVING COUNT(*) > 1
                   ) f ON o.data = f.data
        LEFT OUTER JOIN ( SELECT    [id] = MAX(id)
                          FROM      @table
                          GROUP BY  data
                          HAVING    COUNT(*) > 1
                        ) g ON o.id = g.id
WHERE   g.id IS NULL 

1 个答案:

答案 0 :(得分:0)

所以这就是我为解决问题所做的工作......

---------------------------------------
-- INSERT DUPLICATES INTO TEMP TABLE --
--------------------------------------------------------
IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL 
DROP TABLE #TEMP

SELECT DiagnosisCode
      ,DiagnosisDesc
      ,icd10ThreeCharacter
      ,icd10AdditionalGroup
      ,icd10DiseaseGroup
      ,icd10Level2
      ,icd10Chapter
      ,PMBCDLCode
      ,PMBCDLDescription
      ,PMBCDLRank

INTO #TEMP        
FROM MSOEDW.shared.ICD10
GROUP
  BY DiagnosisCode
    ,DiagnosisDesc
    ,icd10ThreeCharacter
    ,icd10AdditionalGroup
    ,icd10DiseaseGroup
    ,icd10Level2
    ,icd10Chapter
    ,PMBCDLCode
    ,PMBCDLDescription
    ,PMBCDLRank

 HAVING COUNT(DiagnosisCode) > 1

 SELECT [DiagnosisCode]
       ,[DiagnosisDesc]
       ,[icd10ThreeCharacter]
       ,[icd10AdditionalGroup]
       ,[icd10DiseaseGroup]
       ,[icd10Level2]
       ,[icd10Chapter]
       ,[PMBCDLCode]
       ,[PMBCDLDescription]
       ,[PMBCDLRank]
  FROM #TEMP

-----------------------
-- DELETE DUPLICATES --
---------------------------------------------------------
DELETE 
FROM [MSOEDW].[shared].[ICD10]
WHERE EXISTS (
SELECT DISTINCT TMP.*
FROM [MSOEDW].[shared].[ICD10] ICD  
JOIN #TEMP TMP
  ON ICD.DiagnosisCode = TMP.DiagnosisCode
JOIN [MSOEDW].[auth].[AuthHeader] head 
  ON ICD.[icd10Key] = head.[icd10Key]
JOIN [MSOEDW].[claim].[Claim] clm
  ON icd.[icd10Key] = clm.[icd10Key]
  )
------------------------------------------------------------

希望这会在不久的将来帮助其他有同样问题的人