SQL连接多行到单行

时间:2013-11-29 16:11:15

标签: sql sql-server-2008

我正在努力按照我需要的方式进行连接,我有两个表来存放我需要链接的数据(只是为了清楚)。一个表包含出站呼叫数据,拨打的号码,持续时间等。另一张表格显示被拨打的人的联系方式。载列如下:

CustID | Number 1  | Number 2 | Number 3  | Number 4
    1  | 072454584 |          | 017726593 | 
    2  |           |0125456852|           | 0125785448

因此,如果我们想给客户1打电话,我们会尝试两个号码,只有一个连接。

我需要做的是将拨打的号码加入到客户记录中,以便比较每个号码,直到匹配匹配(希望这是有意义的)。我已经尝试了case when声明,但它没有用。这样做的最佳方法是什么?!?!

2 个答案:

答案 0 :(得分:2)

我可能会采用这种方法进行查询。

with myphones
AS
(
    SELECT CustomerId, Phone1 As Phone FROM ContactDetails
    UNION
    SELECT CustomerId, Phone2 As Phone FROM ContactDetails
    UNION
    SELECT CustomerId, Phone3 As Phone FROM ContactDetails
    UNION
    SELECT CustomerId, Phone4 As Phone FROM ContactDetails
)
SELECT p.CustomerId, p.Phone, oc.*
FROM myphones p 
    INNER JOIN outboundcalls oc ON p.Phone = oc.Phone

答案 1 :(得分:2)

你想在匹配中使用一系列左外连接和条件语句:

select cd.CustId,
       coalesce(oc1.number, oc2.number, oc3.number, oc4.number) as MatchingNumber,
       (case when oc1.Number is not null then 'Number1'
             when oc2.Number is not null then 'Number2'
             when oc3.Number is not null then 'Number3'
             when oc4.Number is not null then 'Number4'
        end) as WhichMatch
from ContactDetails cd left outer join
     OutboundCalls oc1
     on cd.number1 = oc1.number left outer join
     OutboundCalls oc2
     on cd.number2 = oc2.number left outer join
     OutboundCalls oc3
     on cd.number3 = oc3.number left outer join
     OutboundCalls oc4
     on cd.number4 = oc4.number;

left outer join尝试匹配列表中的每个号码。 coalesce()将选择第一个匹配的号码,case会告诉您哪个号码匹配。

请注意,如果给定客户有多个成功的出站呼叫,您将在输出中获得多行。

相关问题