【问题标题】:SQL Server - How to combine one-to-many into a single tableSQL Server - 如何将一对多组合到一个表中
【发布时间】:2021-01-16 06:28:37
【问题描述】:

我有一个联系人列表,希望能够连接到 contacts_phone 表,该表具有给定联系人的任意数量的电话。但是当我查询时,我想要一个包含所有可用电话号码的联系人列表。这可能吗?

联系人表

id FirstName LastName etc
1 Liam Smith
2 Noah Johnson
3 Oliver Williams

Contacts_Phone 表

id ContactsId Phone PhoneType
1 1 212-555-1234 Home
2 1 212-555-2314 Cell
3 2 332-555-1324 Cell
4 3 212-555-1432 Cell
5 3 332-555-4213 Work Cell
6 3 347-555-4321 Work
7 3 212-555-4231 Alt

想要的结果

id FirstName LastName etc Phone1 Phone2 Phone3 Phone4
1 Liam Smith 212-555-1234 212-555-2314
2 Noah Johnson 332-555-1324
3 Oliver Williams 212-555-1432 332-555-4213 347-555-4321 212-555-4231

【问题讨论】:

  • 我确实包含了预期的结果。我不知道该尝试什么,抱歉。
  • 如果您可以告诉我Phone 列的绝对最大数量,那么我们可以在没有动态SQL 的情况下做到这一点

标签: sql-server


【解决方案1】:

您将需要更复杂的动态 SQL 解决方案来获得完全符合您要求的结果。

但是,这里有一个可能适合您的非动态 SQL 解决方案。它基本上是为每种手机类型使用一个子查询。

select c.id, c.FirstName, c.LastName, c.etc, 
  (select Phone from Contacts_Phone as cp where cp.ContactsId = c.id and PhoneType = 'Home') as HomePhone,
  (select Phone from Contacts_Phone as cp where cp.ContactsId = c.id and PhoneType = 'Cell') as CellPhone,
  (select Phone from Contacts_Phone as cp where cp.ContactsId = c.id and PhoneType = 'Work Cell') as WorkCellPhone,
  (select Phone from Contacts_Phone as cp where cp.ContactsId = c.id and PhoneType = 'Work') as WorkPhone,
  (select Phone from Contacts_Phone as cp where cp.ContactsId = c.id and PhoneType = 'Alt') as AltPhone 
from Contacts as c

【讨论】:

  • 谢谢!我不知道一个联系人可能有多少个电话号码,所以我无法确定我需要创建多少个子查询
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 2014-09-30
  • 1970-01-01
  • 2014-09-01
  • 2018-04-23
  • 1970-01-01
相关资源
最近更新 更多