插入不同的值SQL Server

时间:2011-09-29 13:03:20

标签: sql-server insert distinct-values

我正在尝试从View中将唯一值插入表中。我有一张桌子如下: “fromView”在护照中没有独特的约束

id  | passport | name | surname | address 
1      44543     John    Smith     xxxxx
2      10001     Mike    Thomps    avasfa
3      10001     Mike    Thomps    avasfa
4      10001     Mike    Thomps    avasfa
5      14221     Robert  Martinez  lkjij3

我的“toTable”具有相同的数据结构,但在护照栏中具有唯一约束。

我的插入查询是:

INSERT into toTable (id, passport, name, surname, address) 
SELECT (id, passport, name, surname, address) 
FROM fromView a 
WHERE passport IS NOT NULL AND NOT EXISTS (SELECT * 
                                           FROM toTable b
                                           WHERE b.passport = a.passport)

但这给了我以下错误:

  

无法在对象'toTable'中插入具有唯一索引'toTable_Passport_Unique'的重复键行。

所以,我不知道如何在表中插入唯一值。提前致谢

4 个答案:

答案 0 :(得分:4)

通过运行此查询,您可以获得包含多个条目的所有护照的列表:

Select Passport, Count (*) NumEntries
From  fromTable
Group by Passport
Having Count (*) > 1

然后你必须决定如何处理这些重复的行。运行以下查询以查看这些重复项的完整行:

Select *
From  fromTable
Where Passport In
(
    Select Passport, Count (*) NumEntries
    From  fromTable
    Group by Passport
    Having Count (*) > 1
)
Order by Passport

假设您决定使用为每个护照插入的最新行(意味着Id将是最高的),此查询将为您提供所需的数据。

Select T1.*
From  fromTable T1
Where Id In
(
    Select Max (Id) Id
    From  fromTable
    Group by Passport
)

您可以使用

进行插入
INSERT into toTable (id, passport, name, surname, address) 
Select T1.*
From  fromTable T1
Where Id In
(
    Select Max (Id) Id
    From  fromTable
    Group by Passport
)

答案 1 :(得分:2)

insert into toTable (id, passport, name, surname, address)
select id, passport, name, surname, address
from (
      select *,
             row_number() over(partition by passport order by id) as rn
      from fromTable
     ) as T
where rn = 1

答案 2 :(得分:0)

如果我们可以假设同一个passport,我们将拥有相同的namesurnameaddress,我们只想要最新的({1}} )id然后尝试,

INSERT INTO toTable (id, passport, name, surname, address)
SELECT max(id), passport, name, surname, address
FROM fromTable
--optional WHERE clause in case there's already data in toTable:
WHERE passport NOT IN (SELECT to.passport from toTable [to])
GROUP BY passport, name, surname, address

答案 3 :(得分:0)

insert into toTable (id, name, surname, addr, passport)
  select
    testA1.id, testA1.name, testA1.surname, testA1.addr, testA1.passport 
  from 
    fromTable as testA1 right join (select min(id) AS distinctID, passport from fromTable group by passport) as testA2 on 
    testA2.distinctID = testA1.id