小编典典

sql查询从同一列中获取一行的多个值

sql

如果每个员工有多个联系方式,我将获得多行,但我只希望每位员工列出他们的姓,名,部门名称,电子邮件和电话。

所以它应该像这样

    First Name    Last Name    Division     Email                  Phone
       Test          Guy         Exec     test@gmail.com        555-5555

这是我所拥有的,但不起作用:

    SELECT sr.LastName, sr.FirstName, dd.Name, 
        Email = (select sc.ContactValue FROM StaffContactInformation as sc
         INNER JOIN StaffRoster as roster on sc.StaffID = roster.ID
         where sc.ContactTypeID = 3 and roster.ID = sr.ID),
Phone = (SELECT sc1.ContactValue FROM StaffContactInformation as sc1 
        INNER JOIN StaffRoster as roster on sc1.StaffID = roster.ID
        where sc1.ContactTypeID = 1) 
    FROM StaffRoster as sr
    left join dictDivisions as dd on sr.DivisionID = dd.Id  
    left join StaffContactInformation as sci on sr.ID = sci.StaffID
    inner join dictStaffContactTypes as dsct on sci.ContactTypeID = dsct.ID 
    where (sr.Active = 1 and sr.isContractor = 0 )
    ORDER BY sr.LastName, sr.FirstName

我用以下查询解决了它:

    SELECT sr.LastName, sr.FirstName, dd.Name, 
        Email = (select sc.ContactValue FROM StaffContactInformation as sc
         INNER JOIN StaffRoster as roster on sc.StaffID = roster.ID
         where sc.ContactTypeID = 3 and roster.ID = sr.ID),
Phone = (SELECT sc.ContactValue FROM StaffContactInformation as sc 
        INNER JOIN StaffRoster as roster on sc.StaffID = roster.ID
        where sc.ContactTypeID = 1 and roster.ID = sr.ID) 
    FROM StaffRoster as sr
    left join dictDivisions as dd on sr.DivisionID = dd.Id 
    where (sr.Active = 1 and sr.isContractor = 0 )
    ORDER BY sr.LastName, sr.FirstName

阅读 213

收藏
2021-04-28

共1个答案

小编典典

如果要选择email,则phone在子查询中,这两个联接可能是不必要的:

left join StaffContactInformation as sci on sr.ID = sci.StaffID
inner join dictStaffContactTypes as dsct on sci.ContactTypeID = dsct.ID

由于它们,您得到的行与特定人的联系人一样多。

最终查询可能类似于:

SELECT sr.LastName, sr.FirstName, dd.Name, 
    Email = (
        select sc.ContactValue FROM StaffContactInformation as sc
        INNER JOIN StaffRoster as roster on sc.StaffID = roster.ID
        where sc.ContactTypeID = 3 and roster.ID = sr.ID
    ),
    Phone = (
        SELECT sc1.ContactValue FROM StaffContactInformation as sc1 
        INNER JOIN StaffRoster as roster on sc1.StaffID = roster.ID
        where sc1.ContactTypeID = 1
    ) 
FROM StaffRoster as sr
left join dictDivisions as dd on sr.DivisionID = dd.Id  
where (sr.Active = 1 and sr.isContractor = 0 )
ORDER BY sr.LastName, sr.FirstName
2021-04-28