使用展平结果加入查询

时间:2010-11-15 14:43:28

标签: sql-server-2008

我有以下实体

alt text

AddressType只是一个枚举字段,用于定义电子邮件是个人/工作/其他。

是否可以执行返回展平结果的查询,如下例中的结果?

CustomerID    Full Name       Personal Email         Work Email
-----------   --------------  -----------------      -----------------------
1             John Doe        johndoe@hotmail.com    john.doe@company.com

2 个答案:

答案 0 :(得分:2)

select c.CustomerID, 
    c.FullName as [Full Name], 
    epersonal.AddressText as [Personal Email], 
    ework.AddressText as [Work Email]
from Customer c
left outer join Email epersonal on c.CustomerID = epersonal.CustomerID 
    and epersonal.AddressType = 'personal'
left outer join Email ework on c.CustomerID = ework.CustomerID 
    and epersonal.AddressType = 'work'

答案 1 :(得分:1)

两个主要选择:

1)选择它为典型(有两行,每封电子邮件一行),然后使用pivot运算符展平。

pivot的例子(我把它称为一个例子,因为我在记事本中写了它。可能有点错误,但它应该指出正确的方法):

select
  CustomerID,
  FullName
  [1] as WorkEmail,
  [2] as HomeEmail
from
  (select 
    c.CustomerID, c.FullName, e.AddressText, e.AddressType
   from 
     Customer c
     join emails e on e.CustomerID = c.CustomerID) as Source
pivot (
  AddressText
  FOR AddressType in ([1], [2])
)

2)两次加入电子邮件表,每种类型的地址一次。建议外联接,如果缺少一个你仍然得到另一个。