SQL Server。从选择中删除

时间:2014-12-15 23:41:29

标签: sql sql-server

我正在使用SQL Server 2012,并进行以下查询。我们称这个查询为A。

SELECT a.col, a.fk
FROM Table1 a
INNER JOIN (
    select b.col
    from Table1 b
    group by b.col
    having count(*) > 1)
b on b.col = a.col

我想只删除从查询A返回的行,特别是与返回的col AND fk

匹配的行

我正在考虑执行以下操作,但它只会删除col上匹配的行。

delete from Table1
where col in (
SELECT a.col
    FROM Table1 a
    INNER JOIN (
        select b.col
        from Table1 b
        group by b.col
        having count(*) > 1)
    b on b.col = a.col)
)

3 个答案:

答案 0 :(得分:3)

使用delete from Join语法

delete t1
from table1 t1
INNER JOIN (SELECT a.col, a.fk
            FROM Table1 a
            INNER JOIN (
                        select b.col
                        from Table1 b
                        group by b.col
                        having count(*) > 1)
                         b on b.col = a.col) t2
ON t1.col1=t2.col1 and t1.fk=t2.fk

答案 1 :(得分:0)

您可以将 col fk 字段组合成另一个唯一字段来检索所需行

delete from Table1
where cast(col as varchar(50))+'//'+cast(fk as varchar(50)) in (
SELECT cast(a.col as varchar(50))+'//'+cast(a.fk as varchar(50))
    FROM Table1 a
    INNER JOIN (
        select b.col
        from Table1 b
        group by b.col   
        having count(*) > 1)
    b on b.col = a.col)
)

答案 2 :(得分:0)

您可以像这样表达查询A:

SELECT col, fk
FROM (
    SELECT a.col, a.fk, COUNT(*) OVER (PARTITION BY a.col) AS [count]
    FROM Table1 a
) counted
WHERE [count] > 1

这导致了一种使用CTE进行DELETE的好方法:

;WITH ToDelete AS (
    SELECT a.col, a.fk, COUNT(*) OVER (PARTITION BY a.col) AS [count]
    FROM Table1 a
)
DELETE FROM ToDelete
WHERE [count] > 1

这确实提供了与问题中的DELETE语句相同的结果。

如果要删除除了一行且具有重复col值的所有行,您可以使用以下内容:

;WITH ToDelete AS (
    SELECT a.col, a.fk
           , ROW_NUMBER() OVER (PARTITION BY a.col ORDER BY a.fk) AS [occurance]
    FROM Table1 a
)
DELETE FROM ToDelete
WHERE [occurance] > 1

ORDER BY子句将确定保留哪一行。