摘要:
详见下文。为了便于阅读,我将[unanswered] 多对多问题复制到顶部:
    Given the "Input" table, what is the SQL to generate the 3rd "Output"
    table (Person_plays_Instrument)?
电流输入(1 个表):
OriginalTable:
PersonId PersonName Instrument_1 Instrument_2 Instrument_3 MailingAddress HomePhone
--------|----------|------------|------------|------------|--------------|------------
1        Bob        Violin       Viola        Trumpet      someplace      111-111-1111
2        Suzie      Cello        Flute        <null>       otherplace     222-222-2222
3        Jim        Violin       <null>       <null>       thirdplace     333-333-3333
所需输出(3 个表):
Person:
Id Name   MailingAddress HomePhone
--|------|--------------|------------
1  Bob    someplace      111-111-1111
2  Suzie  otherplace     222-222-2222
3  Jim    thirdplace     333-333-3333
Instrument:
Id Name
--|-------
1  Violin
2  Cello
3  Viola
4  Flute
5  Trumpet
Person_plays_Instrument:
PersonId InstrumentId
--------|------------
1        1
1        3
1        5
2        2
2        4
3        1
细节:
我有一个单一的平面 SQL 表,它最初是一个电子表格。我想让它正常化。我将把它分成每个表的 1 个问题。
问题 1 和 2 已得到解答,但我将保留它们以防其他人发现它们有帮助。
问题:
问题 #1 : [answered]
如何生成 Person 表?
答案 #1:
这篇精彩的帖子让我了解了 2/3。对于一对多表,我已经准备好了。这是代码:
[add autonumber field to OriginalTable, name it PersonId]
[create empty Person table with Id, Name, MailingAddress, HomePhone fields]
INSERT INTO Person (Id, Name, MailingAddress, HomePhone)
  SELECT o.PersonID, o.PersonName, o.MailingAddress, o.HomePhone
  FROM OriginalTable as o
  WHERE o.PersonName Is Not Null;
问题 #2:[attempted](@Branko 在已接受答案中的更好版本)
如何生成仪器表?
答案 #2:
同样,一对多。起初,多列让我难过。
解决方案分为两部分:
- 我只需要对每列重复一次 INSERT 命令。
- 使用这篇文章和 IN 运算符,我可以每次检查以确认我还没有插入该值。
这是代码:
[create empty Instrument table with Id[autonumber], Name fields]
INSERT INTO Instrument (Name)
  SELECT Distinct o.Instrument_1
  FROM OriginalTable as o
  WHERE o.Instrument_1 Is Not Null
  AND o.Instrument_1 Not In (SELECT Name from Instrument);
INSERT INTO Instrument (Name)
  SELECT Distinct o.Instrument_2
  FROM OriginalTable as o
  WHERE o.Instrument_2 Is Not Null
  AND o.Instrument_2 Not In (SELECT Name from Instrument);
INSERT INTO Instrument (Name)
  SELECT Distinct o.Instrument_3
  FROM OriginalTable as o
  WHERE o.Instrument_3 Is Not Null
  AND o.Instrument_3 Not In (SELECT Name from Instrument);
问题 #3 : [unanswered]
如何生成 Person_plays_Instrument 表?