基于两列删除行

时间:2019-05-03 16:50:36

标签: sql sql-server

如何仅基于两个列条件删除行。

示例

Table 1

id  name  phone
1   aa    123
1   aa    345
1   bb    123
2   aa    456
1   NULL  123
1         123

我的预期输出

id name phone 
1  bb   123
2  aa   456

我要删除的条件:如果ID和名称相同,则删除行 如果条件中的值之一为null或空白,则还应删除输入中给定的行。

3 个答案:

答案 0 :(得分:0)

这应该做您想要的。您可以出于测试目的首先进行选择,然后删除选择并取消注释删除。

-- This joins on the table the set of data that has more then 1 row with duplicate IDs, and names.  Then you can delete from here.
    --DELETE t1
    SELECT * 
    FROM Table1 T1
    INNER JOIN (
        -- this gets all the records that have more then 1 ID and Name that are the same.
        SELECT ID, name
        FROM Table1
        GROUP BY ID, name
        HAVING COUNT(*) > 1
    ) ToDelete ON T1.ID = ToDelete.ID
    AND T1.name = ToDelete.name

答案 1 :(得分:0)

Delete from table1 t where exists (
Select * from 
(Select id, name from table1 group by id, name having count(*) > 1) t2 where t.id = t2.id and t.name = t2.name)

答案 2 :(得分:0)

create table #tablea (
    id int,
    name varchar(3),
    phone int
)

insert into #tablea (id, name, phone)
values
    (1,'aa','123'),
    (1,'aa','345'),
    (1,'bb','123'),
    (2,'aa','456')

select * from #tablea

delete a
from #tablea a
inner join (
    select id, name
    from #tablea
    group by id, name
    having COUNT(*) > 1
) b on a.id = b.id and a.name = b.name

select * from #tablea

drop table #tablea