删除重复的观察和其他指定的行

时间:2013-06-04 17:21:54

标签: sql-server-2008

id     operation     age     shoesize
1        .            24        12
2        .            23        10
1        .            24        11   
3        R -          24         9
4        .            25       -9.5

我想删除重复的行,带有' R - '的行,以及带有shoeize< 0的行。

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

假设id无法复制,您可以执行以下操作:

;WITH CTE AS
(
    SELECT  id,
            operation,
            age,
            shoesize,
            N = COUNT(*) OVER(PARTITION BY operation, age, shoesize)
    FROM YourTable
)
DELETE FROM CTE
WHERE N > 1
OR operation = 'R -'
OR shoesize < 0

如果重复项需要考虑id,则:

;WITH CTE AS
(
    SELECT  id,
            operation,
            age,
            shoesize,
            N = COUNT(*) OVER(PARTITION BY id, operation, age, shoesize)
    FROM YourTable
)
DELETE FROM CTE
WHERE N > 1
OR operation = 'R -'
OR shoesize < 0

如果您只需要删除重复的行,并希望保留其中一行,那么您需要执行以下操作:

;WITH CTE AS
(
    SELECT  id,
            operation,
            age,
            shoesize,
            RN = ROW_NUMBER() OVER(PARTITION BY id, operation, age, shoesize ORDER BY id)
    FROM YourTable
)
DELETE FROM CTE
WHERE RN > 1
OR operation = 'R -'
OR shoesize < 0

答案 1 :(得分:0)

delete from table_name
where operation ='R -'
or cast(shoesize as int)< 0

<强> SQL Fiddle

<强> Edit

delete t1
from Table1 t1
inner join (select ROW_NUMBER()over 
(partition by id, operation, age, shoesize order by id, operation, age, shoesize) 
AS [row_id],* from Table1)t2
on t1.operation=t2.operation and t1.[age]=t2.[age] and t1.shoesize=t2.shoesize
where t2.row_id>1
or t1.[operation] ='R -'
or cast(t1.shoesize as int)< 0

<强> SQL Fiddle