在另一个表中插入共享给定值的第一行的id,以及每个重复行的另一个值

时间:2015-08-25 18:55:29

标签: sql sql-server normalization

对标题感到抱歉 - 我很难简洁地说出来

所以我有一些数据当前都在一个表中,我希望将它存储在两个不同的表中。这是我的情况的简单版本:

Person:
+----+-----------+----------+----------+
| Id | FirstName | LastName | City     |
+----+-----------+----------+----------+
| 1  | Billy     | Bob      | Toronto  |
| 2  | Billy     | Bob      | Mumbai   |
| 3  | Sally     | Ann      | Toronto  |
| 4  | Joe       | Hall     | New York |
| 5  | Joe       | Hall     | Boston   |
+----+-----------+----------+----------+

所以我有一群人和他们的城市。我想这样做,所以给定的名字/姓氏组合只出现一次,第二个表描述名称id< - >城市组合,如此:

Person:
+----+-----------+----------+
| Id | FirstName | LastName |
+----+-----------+----------+
| 1  | Billy     | Bob      |
| 3  | Sally     | Ann      |
| 4  | Joe       | Hall     |
+----+-----------+----------+
LivesIn:
+----------+----------+
| PersonId | City     |
+----------+----------+
| 1        | Toronto  |
| 1        | Mumbai   |
| 3        | Toronto  |
| 4        | New York |
| 4        | Boston   |
+----------+----------+

我的问题是:如何只选择每个名称组合的第一个实例插入第二个表?为了准确地移动数据,我可以这样做:

INSERT INTO LivesIn (PersonId, City)
SELECT Id, City
FROM Person

但这意味着LivesIn仍会有两个不同的PersonId到同一个名称组合。

1 个答案:

答案 0 :(得分:2)

INSERT INTO LivesIn (PersonId, City)
select t1.id, t2.City
from 
(
  SELECT min(Id) as id, FirstName, LastName
  FROM Person
  GROUP BY FirstName, LastName
) t1
join person t2 on t1.FirstName = t2.FirstName 
              and t1.LastName = t2.LastName