删除特定列中具有重复列数据的行

时间:2013-01-20 09:12:50

标签: sql

我有一个表,我们将其中的一堆垃圾数据称为Table1,并且没有唯一的标识符列。

我想从Table1中选择一些列并将数据传输到Table2。但是,在传输之后,我需要删除Table2中的行,并在3列中删除重复项。

假设我在表2中有一行,其中包含已转移的列[FirstName][LastName][CompanyName][City][State]。我只想保留具有[FirstName][LastName][CompanyName]的唯一组合的行。为了增加混淆,[LastName]和/或[CompanyName]可能包含NULL值。我怎么能做到这一点?提前感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

可以使用distinct关键字创建唯一条目。

select distinct 
       FirstName, 
       LastName, 
       CompanyName 
  from MyTable

因此,如果您发出以下命令,则只会向新表添加不同的值

insert into newTable
(
       FirstName, 
       LastName, 
       CompanyName 
)
select distinct 
       FirstName, 
       LastName, 
       CompanyName 
  from MyTable
 where not exists (
   select 1 from newTable 
    where newTable.FirstName   = MyTable.FirstName
      and newTable.LastName    = MyTable.LastName
      and newTable.CompanyName = MyTable.CompanyName
  ) 

可以使用'MERGE'命令完成向表中添加不同新值的另一种好方法。

merge newtable as target
using (select distinct 
              FirstName, 
              LastName, 
              CompanyName 
         from MyTable
       ) as source
   on target.FirstName   = target.FirstName
  and target.LastName    = target.LastName
  and target.CompanyName = target.CompanyName

when not matched by target then
  insert (FirstName, 
          LastName, 
          CompanyName)
  values (target.FirstName, 
          target.LastName, 
          target.CompanyName);

MERGE命令为您提供了控制何时同步表的选项。

答案 1 :(得分:0)

看这里的例子,可能这就是你想要的...... link

insert into Table2(`firstname` , `lastname` , `companyname`)
select a.firstname,a.lastname,a.companyname 
from 
(select distinct(concat(firstname,',',lastname,',',companyname))
,firstname,lastname,companyname from Table1) a;

答案 2 :(得分:0)

create table t2
as
select distinct FirstName,LastName,CompanyName,City,State from t1;

with the below query u 'll get to know we have duplicate entries or not.
select FirstName,LastName,CompanyName,count(*) from t2
group by FirstName,LastName,CompanyName
having Count(*) >1;

delete from t2 a where rowid not in (select min(rowid) from t2 b where a.column1=b.column1 
and .....);