将多对多关系转变为单行

时间:2016-10-03 01:50:11

标签: sql-server tsql

我有以下表格

Users

Id
FirstName
LastName

样本数据

1,'Peter','Smith'
2,'John','Como'

Phones

Id
UserId
PhoneTypeId
Phone
ContactName

示例数据

1,1,4,'555-555-5551','Peter'
2,1,4,'555-555-5552','Paul'
3,1,4,'555-555-5553','Nancy'
4,1,4,'555-555-5554','Hellen'

PhoneTypes

Id
Type

包含样本数据

1 Home
2 Work
3 Cell
4 Emergency

我必须创建以下结果

UserId, UserFirstName, UserLastName, FirstEmergencyContactName, FirstEmergencyContactPhone, SecondEmergencyContactName, SecondEmergencyContactPhone, ThirdEmergencyContactName, ThirdEmergencyContactPhone, FourthEmergencyContactName, FourthEmergencyContactPhone, FifthEmergencyContactName, FifthEmergencyContactPhone

如何为每个拥有紧急​​联系人的用户创建一行?有些用户可能有一个紧急联系人,有些用户可能有很多,但我只需要其中的五个。

2 个答案:

答案 0 :(得分:1)

这称为表旋转。由于您希望的结果不超过5个,因此您可以conditional aggregation使用row_number

select id, firstname, lastname,
       max(case when rn = 1 then contactname end) emergency_contact1,
       max(case when rn = 1 then phone end) emergency_phone1,
       max(case when rn = 2 then contactname end) emergency_contact2,
       max(case when rn = 2 then phone end) emergency_phone2,
       ...
from (
    select u.id, u.firstname, u.lastname, p.phone, p.contactname, 
           row_number() over (partition by u.id order by p.phonetypeid) rn
    from users u 
       join phones p on u.id = p.userid
) t
group by id, firstname, lastname

答案 1 :(得分:1)

此外,您可以使用透视,无需动态SQL和硬编码,因为您只需要5个联系人/电话。示例如下:

Row

输出:

;WITH cte AS (
SELECT  p.UserId, 
        FirstName, 
        LastName,
        CAST(ContactName as nvarchar(100)) as ContactName,
        CAST(Phone as nvarchar(100)) as ContactPhone,
        CAST(ROW_NUMBER() OVER (PARTITION BY p.UserId ORDER BY pt.Id) as nvarchar(100)) as RN
FROM Users u
INNER JOIN Phones p
    ON p.UserId = u.Id
INNER JOIN PhoneTypes pt
    ON pt.Id = p.PhoneTypeId
WHERE pt.Id = 4
)

SELECT *
FROM (
    SELECT  UserId, 
            FirstName, 
            LastName,
            [Columns]+RN as [Columns],
            [Values]
    FROM cte
    UNPIVOT (
        [Values] FOR [Columns] IN (ContactName, ContactPhone)
    ) as unp
) as t
PIVOT (
    MAX([Values]) FOR [Columns] IN (ContactName1,ContactPhone1,ContactName2,ContactPhone2,ContactName3,ContactPhone3,
ContactName4,ContactPhone4,ContactName5,ContactPhone5)
) as pvt

我添加了更多联系人。