根据T-SQL中的源表填充列数据

时间:2013-03-14 19:32:36

标签: sql tsql sql-server-2008-r2 unpivot

我不确定我的问题是否措辞正确,但现在也是如此。

我有一个名为Contacts的表,其中包含表格地址,电子邮件,电话的FK引用(这些表包含1到多个联系人)。我需要创建一个将提取所有数据的查询,并且有一个名为Contact Method的列,该列显示该行来自哪个子表。

Contact: ID, AddressID, EmailID, PhoneID
Address: ID, Line1, City, State
Email :  ID, EAddress
Phone :  ID, Number, Extension

我需要结果表看起来像这样:

ContactMethod | ID | [Value1] | [Value2] | [Value3]

Address         2      N5980    Onalaska     WI
Email           8     myEmail@
Phone           5     555-5555    1234

或者它可以列出一行中的所有组合列,如果这更简单,我也可以使用它。即。

ContactMethad | ID | Line1 | City | State | ID | EAddress | ID | Number | Extension

我看了PIVOT,这很整洁,但似乎并没有解决我的问题。我是否需要将其与COALESCE结合使用?

感谢您的帮助。


修改

我的数据,表格上的联系方式如下:

ID | AddressID | PhoneID | EmailID

1      3           null      null
2     null         null      7
3     null          5        null
4     4            null      null
5     null         6         null

建议的解决方案有效,只是每个ID获得3行。有意义吗?

2 个答案:

答案 0 :(得分:7)

您可以使用CROSS APPLYVALUES子句取消数据来获取结果:

select d.ContactMethod, d.id, d.Value1, d.Value2, d.Value3
from contacts c
left join address a
  on c.addressid = a.id
left join email e
  on c.emailid = e.id
left join phone p
  on c.phoneid = p.id
cross apply
(
  values
    ('Address', c.addressid, a.Line1, a.City, a.State),
    ('Email', c.emailid, e.eAddress, '', ''),
    ('Phone', c.phoneid, p.number, cast(p.extension as varchar(10)), '')
) d (ContactMethod, id, Value1, Value2, Value3)

请参阅SQL Fiddle with Demo

这给出了结果:

| CONTACTMETHOD | ID |   VALUE1 |   VALUE2 | VALUE3 |
-----------------------------------------------------
|       Address |  2 |    N5980 | Onalaska |     WI |
|         Email |  8 | myEmail@ |          |        |
|         Phone |  5 | 555-5555 |     1234 |        |

如果您想要第二个结果,那么您可以使用多个连接来获取它:

select cm.ContactMethod,
  a.id addressid,
  a.line1,
  a.city,
  a.state,
  e.id emailid,  
  e.eaddress,
  p.id phoneid,
  p.number,
  p.extension
from contacts c
cross join
(
  VALUES ('Address'),('Email'),('Phone')
) cm (ContactMethod)
left join address a
  on c.addressid = a.id
  and cm.ContactMethod = 'Address'
left join email e
  on c.emailid = e.id
  and cm.ContactMethod = 'Email'
left join phone p
  on c.phoneid = p.id
  and cm.ContactMethod = 'Phone';

SQL Fiddle with Demo。结果是:

| CONTACTMETHOD | ADDRESSID |  LINE1 |     CITY |  STATE | EMAILID | EADDRESS | PHONEID |   NUMBER | EXTENSION |
----------------------------------------------------------------------------------------------------------------
|       Address |         2 |  N5980 | Onalaska |     WI |  (null) |   (null) |  (null) |   (null) |    (null) |
|         Email |    (null) | (null) |   (null) | (null) |       8 | myEmail@ |  (null) |   (null) |    (null) |
|         Phone |    (null) | (null) |   (null) | (null) |  (null) |   (null) |       5 | 555-5555 |      1234 |

编辑#1,根据您的更改,您可以将查询更改为以下内容。

第一个包含三个value列,然后您只需添加WHERE子句即可过滤掉null个值:

select c.ID, ContactMethod, Value1, Value2, Value3
from contacts c
left join address a
  on c.addressid = a.id
left join email e
  on c.emailid = e.id
left join phone p
  on c.phoneid = p.id
cross apply
(
  values
    ('Address', c.addressid, a.Line1, a.City, a.State),
    ('Email', c.emailid, e.eAddress, null, null),
    ('Phone', c.phoneid, p.number, cast(p.extension as varchar(10)), null)
) d (ContactMethod, id, Value1, Value2, Value3)
where value1 is not null
  or value2 is not null
  or value3 is not null

SQL Fiddle with Demo。结果是:

 ID | CONTACTMETHOD |            VALUE1 |    VALUE2 | VALUE3 |
---------------------------------------------------------------
|  1 |       Address |             N5980 |  Onalaska |     WI |
|  2 |         Email |          myEmail@ |    (null) | (null) |
|  3 |         Phone |          555-5555 |      1234 | (null) |
|  4 |       Address | 1417 Saint Andrew | La Crosse |     WI |

如果您想将结果放在一行中,那么您将需要使用UNPIVOT函数:

select *
from
(
  select id,
    case col 
      when 'addressid' then 'address'
      when 'emailid' then 'email'
      when 'phoneid' then 'phone' end ContactMethod,
    contact_id
  from contacts
  unpivot
  (
    contact_id
    for col in (addressid, emailid, phoneid)
  ) unpiv
) c
left join address a
  on c.contact_id = a.id
  and c.ContactMethod = 'Address'
left join email e
  on c.contact_id = e.id
  and c.ContactMethod = 'Email'
left join phone p
  on c.contact_id = p.id
  and c.ContactMethod = 'Phone';

SQL Fiddle with Demo。此查询的结果是:

| ID | CONTACTMETHOD | CONTACT_ID |             LINE1 |      CITY |  STATE | EADDRESS |   NUMBER | EXTENSION |
--------------------------------------------------------------------------------------------------------------
|  1 |       address |          2 |             N5980 |  Onalaska |     WI |   (null) |   (null) |    (null) |
|  2 |         email |          8 |            (null) |    (null) | (null) | myEmail@ |   (null) |    (null) |
|  3 |         phone |          5 |            (null) |    (null) | (null) |   (null) | 555-5555 |      1234 |
|  4 |       address |          3 | 1417 Saint Andrew | La Crosse |     WI |   (null) |   (null) |    (null) |

答案 1 :(得分:0)

进入第二列布局要容易得多。为此你只需要加入:

SELECT *
FROM dbo.Contact c
JOIN dbo.Address a
ON c.AddressID = a.ID
JOIN dbo. Email e
ON c. EmailID = e.ID
JOIN dbo. Phone p
ON c. PhoneID = p.ID

我刚刚使用了SELECT *,但您必须实际列出所有列,因为您不想要所有列。如果您不必在每个子表中都有一行,则需要使用LEFT OUTER JOIN而不是JOIN

有关JOIN的详细信息,请查看此系列:http://sqlity.net/en/1146/a-join-a-day-introduction/


如果您需要多行,可以使用:

SELECT *
FROM dbo.Contact c
CROSS JOIN (VALUES('Address','Email','Phone'))X(ContactMethod)
LEFT JOIN dbo.Address a
ON c.AddressID = a.ID
AND X.ContactMethod = 'Address'
LEFT JOIN dbo. Email e
ON c. EmailID = e.ID
AND X.ContactMethod = 'Email'
LEFT JOIN dbo. Phone p
ON c. PhoneID = p.ID
AND X.ContactMethod = 'Phone'

使用“展开”版本的优点是您不必处理数据类型不兼容。