SQL删除多个联接

时间:2012-08-28 12:20:24

标签: sql sql-server-2008

我有一些具有挑战性的删除声明,我需要帮助。我正在尝试删除同一个表上具有多个连接的多个重复记录。

以下是我的数据示例

versionid(PK)FileID(FK)版本DeleteDate DeleteIndicator

   1              1         1      12/01/2003        1
   2              1         1      12/02/2003        1 
   3              1         1         null           0
   4              2         2      01/02/2004        1
   5              2         2      01/03/2005        1
   6              2         2      01/03/2006        1

我需要删除的数据是FileId和版本匹配的所有重复数据,其中DeleteDate小于04/01/2011而DeleteIndicator = 1.但是,我需要保留最高的VersionID具有相同FileId和Version

的数据

删除后我会剩下这个:

versionid(PK)FileID(FK)版本DeleteDate DeleteIndicator

  2              1         1      12/02/2003        1 
  3              1         1         null           0
  6              2         2      01/03/2006        1

我有一个选择w /多个连接,可以给我上面的记录。我只是不知道如何将其转换为删除语句。这是我的选择陈述。

SELECT  t.VersionID ,
    t.FileID ,
    t.version ,
    COUNT(*) ,
    t.DeleteDate ,
    t.DeleteIndicator
FROM    tblFileVersions t
    JOIN ( SELECT   VersionID ,
                    FileID ,
                    MAX(VersionID) AS MaxVersion ,
                    DeleteDate ,
                    DeleteIndicator
           FROM     tblFileVersions
           GROUP BY VersionID ,
                    FileID ,
                    DeleteDate ,
                    DeleteIndicator
         ) x ON t.FileID = x.FileID
WHERE   t.DeleteDate < '2011/04/01'
    AND t.DeleteIndicator = 1
    AND t.VersionID < MaxVersion
GROUP BY t.VersionID ,
    t.FileID ,
    t.version ,
    t.DeleteDate ,
    t.DeleteIndicator ,
    Version
HAVING  COUNT(*) > 1

我需要做的就是拿走我拥有的东西并将其作为删除声明。对不起,如果我的文字格式搞砸了,这是我第一次在这里发布。感谢你的时间,任何帮助都会很棒。

2 个答案:

答案 0 :(得分:1)

最简单的方法就是这样做:

DELETE FROM tblFileVersions 
WHERE VersionID NOT IN (SELECT  t.VersionID
FROM    tblFileVersions t
    JOIN ( SELECT   VersionID ,
                    FileID ,
                    MAX(VersionID) AS MaxVersion ,
                    DeleteDate ,
                    DeleteIndicator
           FROM     tblFileVersions
           GROUP BY VersionID ,
                    FileID ,
                    DeleteDate ,
                    DeleteIndicator
         ) x ON t.FileID = x.FileID
WHERE   t.DeleteDate < '2011/04/01'
    AND t.DeleteIndicator = 1
    AND t.VersionID < MaxVersion
GROUP BY t.VersionID ,
    t.FileID ,
    t.version ,
    t.DeleteDate ,
    t.DeleteIndicator ,
    Version
HAVING  COUNT(*) > 1) 

答案 1 :(得分:0)

只需将您的查询用作子查询,但只选择一个PK字段versionID:

Delete from tblFileVersions where 
versionid NOT IN (select t.VersionID from tblFileVersions t Join...CONTINUE YOUR QUERY HERE......)