3

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

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

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

4

3 回答 3

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 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命令为您提供了控制何时同步表的选项。

于 2013-01-20T09:26:29.630 回答
0

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

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;
于 2013-01-20T09:30:09.253 回答
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 .....);
于 2013-01-20T09:36:36.890 回答