改为使用枢轴来减少连接?

时间:2014-04-17 19:45:29

标签: sql sql-server

我正在为我的网络应用程序创建一些视图。我有单独的表来管理我的电子邮件和电话表到我的员工表。我试图看看是否有办法将大量相同的信息来自同一个表时,将这些表中的大量连接减少为一个数据透视。

我的查询:

SELECT *
FROM (SELECT emp.[first_name] as [First Name]
        ,emp.[last_name] as [Last Name]
        ,emp.[birth_day] as [Birthday]
        ,emp.[gender] as [Gender]
        ,emp.[address_line_1] as [Address]
        ,emp.[address_line_2] as [Apt/Suite #]
        ,emp.[city] AS [City]
        ,emp.[state] AS [State]
        ,emp.[zip] AS [Zip Code]
        ,phone1.[Home Phone Number]
        ,phone2.[Work Phone Number]
        ,phone3.[Mobile Phone Number]
        ,email1.[Primary Email]
        ,email2.[Secondary Email]
        ,email3.[Personal Email]

    FROM [employee].[employees] emp
LEFT JOIN
    ( 
    SELECT TOP 1 [phone_number] AS [Home Phone Number]
        ,[employee_id]
    FROM [employee].[phone_manager] 
    WHERE ([phone_type] = '1')
    ORDER BY [date_added] DESC
    ) phone1 ON phone1.employee_id = emp.employee_id
LEFT JOIN
    ( 
    SELECT TOP 1 [phone_number] AS [Work Phone Number]
        ,[employee_id]
    FROM [employee].[phone_manager] 
    WHERE ([phone_type] = '2')
    ORDER BY [date_added] DESC
    ) phone2 ON phone2.employee_id = emp.employee_id
LEFT JOIN
    ( 
    SELECT TOP 1 [phone_number] AS [Mobile Phone Number]
        ,[employee_id]
    FROM [employee].[phone_manager] 
    WHERE ([phone_type] = '3')
    ORDER BY [date_added] DESC
    ) phone3 ON phone3.employee_id = emp.employee_id
LEFT JOIN
    ( 
    SELECT TOP 1 [email] AS [Primary Email]
        ,[employee_id]
    FROM [employee].[email_manager] 
    WHERE ([email_type] = '1')
    ORDER BY [date_added] DESC
    ) email1 ON email1.employee_id = emp.employee_id
LEFT JOIN
    ( 
    SELECT TOP 1 [email] AS [Secondary Email]
        ,[employee_id]
    FROM [employee].[email_manager] 
    WHERE ([email_type] = '2')
    ORDER BY [date_added] DESC
    ) email2 ON email2.employee_id = emp.employee_id
LEFT JOIN
    ( 
    SELECT TOP 1 [email] AS [Personal Email]
        ,[employee_id]
    FROM [employee].[email_manager] 
    WHERE ([email_type] = '3')
    ORDER BY [date_added] DESC
    ) email3 ON email3.employee_id = emp.employee_id
) pvt

1 个答案:

答案 0 :(得分:2)

你可以在每个"经理身上做你想做的事情。表格,使用row_number()group by。以下是电话号码的示例:

SELECT employee_id,
       MAX(CASE WHEN seqnum = 1 and phone_type = 1 THEN phone_number END) as Home,
       MAX(CASE WHEN seqnum = 1 and phone_type = 2 THEN phone_number END) as Work,
       MAX(CASE WHEN seqnum = 1 and phone_type = 3 THEN phone_number END) as Mobile
FROM (SELECT employee_id, phone_number,
             row_number() over (partition by phone_type order by date_added desc) as seqnum
      FROM employee.phone_manager 
     ) ep
GROUP BY employee_id;