根据其类型将联系人详细信息分组到 SQL 中的单独列中

Grouping Contact details into separate columns in SQL based on its type

我在联系人栏中有多个 phone 号码、多个电子邮件地址、多个传真地址。我需要一个查询来获得如下结果

Contact Id |Phone                 |Email                       |Fax
1          |Phone1, Phone2, Phone3|Email1, Email2,Email3,Email4|Fax1, Fax2
2          |Phone1, Phone2        |Email1, Email2,Email3       |Fax1, Fax2

我的输入是这样的

Value    MeansOfCommunicationDescription    ContactId
email1@port2.com    Email    2
www.1_port2.com    Web Site    2
Test Insert    Fax    2
Test Insert    Web Site    2
Test Insert    Web Site    2
Test Insert    Web Site    2
Test Insert    Web Site    2
Test Insert    Web Site    2
Test Insert    Web Site    2
test     Phone    2
test     Phone    2
test     Phone    2
Test Insert    Web Site    2
Test Insert    Email    2

如果你的数据库版本是2017+,你可以使用string_agg()函数

select ContactId,
       string_agg(phone,',') within group (order by phone) as phone,
       string_agg(email,',') within group (order by email) as email,
       string_agg(fax,',') within group (order by fax) as fax
  from tab
 group by ContactId

您可以使用 CTE 来获得您想要的结果。您可以尝试以下查询:

;WITH ctePhone
    AS (
        SELECT DISTINCT ContactId           [ID],
        STUFF(( SELECT N', ' + Phone
            FROM Table1 B
             WHERE B.ContactId = A.ContactId
                FOR XML PATH(''), TYPE
                    ).value('(.)', 'NVARCHAR(MAX)'), 1, 1, '') [Phone],
        STUFF(( SELECT N', ' + Email
            FROM Table1 B
             WHERE B.ContactId = A.ContactId
                FOR XML PATH(''), TYPE
                    ).value('(.)', 'NVARCHAR(MAX)'), 1, 1, '') [Email],
        STUFF(( SELECT N', ' + Fax
            FROM Table1 B
             WHERE B.ContactId = A.ContactId
                FOR XML PATH(''), TYPE
                    ).value('(.)', 'NVARCHAR(MAX)'), 1, 1, '') [Fax]
            FROM Table1 A
    )
SELECT DISTINCT #Table1.ContactId,
    ctePhone.Phone,
    ctePhone.Email,
    ctePhone.Fax
FROM Table1
    INNER JOIN ctePhone
        ON Table1.ContactId = ctePhone.[ID]