基于三列唯一ID从sql中删除不需要的行

时间:2016-06-29 17:55:18

标签: sql nested distinct sql-delete

这是代码。我做的事情是愚蠢的 - 它是什么?我得到的只是“语法错误”。

select 
    code, shortDescription, longDescription, fullDescripton, 
    codeType, useThruDate, updateDate, updateComment, createDate
into 
    #irish
from 
    (select distinct 
         code, shortDescription, longDescription
         when count(code + shortDescription + longDescription) > 1
             then delete from #irish where useThruDate <> '2016-30-06'
              else 0
        )
from [dbo].[irish]
code        shortDescription    longDescription                             fullDescription             codeType    useThruDate     updat‌​eDate    updateComment                   createDate 
312291001   47113               Sample text for a description (from 2012)   NULL                        DB1         2016-30-04      2016-06-06    merged all tables together.     NULL 
312291001   47113               Sample text for a description (from 2012)   Lorem ippsum lorem ippsum   DB1         2016-30-06      2016-06-06    merged all tables together.     NULL 
312291001   47113               Sample text for a description (from 2012)   Lorem ippsum lorem ippsum   DB2         2016-31-05      2016-06-06    merged all tables together.     NULL

1 个答案:

答案 0 :(得分:0)

我相信这是你的目标:

/* Creates #irish table */    
CREATE TABLE #irish (
        code NVARCHAR(MAX)
        ,shortdescription NVARCHAR(MAX)
        ,longdescription NVARCHAR(MAX)
        ,fulldescription NVARCHAR(MAX)
        ,codeType NVARCHAR(MAX)
        ,useThruDate NVARCHAR(MAX)
        ,updateDate NVARCHAR(MAX)
        ,updateComment NVARCHAR(MAX)
        ,createDate NVARCHAR(MAX)
   /* insert select into #irish table */ 
    INSERT INTO #irish

    SELECT DISTINCT
    Code,ShortDescription,LongDescription, fullDescripton, 
        codeType, useThruDate, updateDate, updateComment, createDate
    FROM dbo.irish
    WHERE 
    useThruDate <> '2016-30-06'
    /* My best understanding of your count critera */ 
    AND (code IS NOT NULL
    OR shortdescription IS NOT NULL
    OR longdescription IS NOT NULL)

    /* selects records from #irish table (which we inserted in the last section) */
    SELECT * FROM #irish
    DROP TABLE #irish

值得注意的是,在此查询中使用临时表具有很小的好处,如果有的话。

我希望这会有所帮助。您的原始代码存在一些问题(请参阅Gordon的评论),因此如果您想深入挖掘,我建议您阅读一些教程。 W3是一个很好的起点。