如何制作单个id列

时间:2015-07-30 13:14:00

标签: sql sql-server-2012

我的id列正在重复,因为用户拥有多个商务手机,如何使用单个ID创建一行。

节目..

84  NULL    8018xxxx        NULL    NULL    NULL
84  80177xxx    NULL        416-xxx NULL    NULL
84  80177xxx    NULL        NULL    NULL    NULL
85  (801) 610-xxx   NULL    NULL    NULL    NULL
86  18005xxx    NULL        NULL    NULL    NULL

我想这样结果......

84  80177xxx       8018xxxx     416-xxx NULL    NULL
85  (801) 610-xxx   NULL        NULL    NULL    NULL
86  18005xxx        NULL        NULL    NULL    NULL

我的sql

Select distinct 
   p.id,
    Case 
        When ph.PhoneLabelId = 3 Then CONVERT(VARCHAR(MAX),ph.DisplayPhone)          
    End as [Business Phone],
    Case 
        When ph.PhoneLabelId = 11 Then CONVERT(VARCHAR(MAX),ph.DisplayPhone)
    End as [Mobile Phone],
    Case 
        When ph.PhoneLabelId = 13 Then CONVERT(VARCHAR(MAX),ph.DisplayPhone)
    End as [Home Phone],
    Case 
        When ph.PhoneLabelId = 5 Then CONVERT(VARCHAR(MAX),ph.DisplayPhone)
    End as [Assistant],
    Case 
        When ph.PhoneLabelId = 5 Then CONVERT(VARCHAR(MAX),ph.DisplayPhone)
    End as [Other]
    from People p
    left join [phone] ph on p.id = ph.PeopleId  

1 个答案:

答案 0 :(得分:0)

您需要GROUP BY子句将“重复项”聚合到一行中。您可能需要使用ISNULL(MAX(),'')包装Case Statements来处理NULLS。

Select distinct 
   p.id,
    MAX(Case 
        When ph.PhoneLabelId = 3 Then CONVERT(VARCHAR(MAX),ph.DisplayPhone)          
    End) as [Business Phone],
    MAX(Case 
        When ph.PhoneLabelId = 11 Then CONVERT(VARCHAR(MAX),ph.DisplayPhone)
    End )as [Mobile Phone],
    MAX(Case 
        When ph.PhoneLabelId = 13 Then CONVERT(VARCHAR(MAX),ph.DisplayPhone)
    End) as [Home Phone],
    MAX(Case 
        When ph.PhoneLabelId = 5 Then CONVERT(VARCHAR(MAX),ph.DisplayPhone)
    End) as [Assistant],
    MAX(Case 
        When ph.PhoneLabelId = 5 Then CONVERT(VARCHAR(MAX),ph.DisplayPhone)
    End) as [Other]
    from People p
    left join [phone] ph on p.id = ph.PeopleId
    GROUP BY p.Id