使用别名表选择相同列两次

时间:2016-04-26 17:04:31

标签: sql database ms-access relational-database

以下是我正在使用的表格的示例。这些仅代表与我的查询相关的列

_Requirements

    RequirementID             fkOwningWsID
    -------------------------------------------    
    REQ-RPT-01                1
    REQ-RPT-02                2

_Workstream

    pk             WsNm
    -------------------------------------------    
    1               Workstream1
    2               Workstream2

mnWorkstream_Leads

    fkWsID          fkEeID
    -------------------------------------------    
    1               1
    1               2
    2               1
    2               2

下表是工会的结果。员工可以来自不同的公司,下面的联合会列出所有员工ID,来自公司1的员工的ID(否则为0)和公司2的员工ID(否则为0)

qryTrackerAllEeList

    EeID             Company1_ID           Company2_ID
    -------------------------------------------    
    1                 1                     0
    2                 0                     2

我正在尝试查看以下结果

    RequirementID        WsNm          Company1_Lead      Company2_Lead
    --------------------------------------------------------------------   
    REQ-RPT-01           Workstream1    1                  2
    REQ-RPT-02           Workstream2    1                  2

我发布了以下SQL

 SELECT DISTINCT Req.RequirementID,  Ws.Wsnm, company1_id.ee_id, company2_id.ee_id
FROM (((([_Requirements] AS Req 
INNER JOIN [_Workstream] AS Ws ON Req.fkOwningWsID = Ws.pkWsID)
INNER JOIN [mnWorkstream_Leads] AS wsLeads ON Ws.pkWsID = wsLeads.fkWsID)
LEFT OUTER JOIN qryTrackerAllEeList AS company1 ON wsLeads.fkEeID = company1.Company1_ID)
LEFT OUTER JOIN qryTrackerAllEeList AS company2 ON wsLeads.fkEeID = company2.Company2_ID)

但问题是我检索了以下结果

    RequirementID        WsNm          Company1_Lead      Company2_Lead
    --------------------------------------------------------------------   
    REQ-RPT-01           Workstream1                       2
    REQ-RPT-01           Workstream1    1                  
    REQ-RPT-02           Workstream2                       2    
    REQ-RPT-02           Workstream2    1

有关如何消除这些重复行和空值的任何建议吗?

1 个答案:

答案 0 :(得分:2)

使用MAX()GROUP BY仅选择非空值并将它们分组到一行:

SELECT DISTINCT Req.RequirementID,  Ws.Wsnm, 
MAX(company1_id.ee_id) as Company1_Lead, MAX(company2_id.ee_id) as Company2_Lead,
FROM (((([_Requirements] AS Req 
INNER JOIN [_Workstream] AS Ws ON Req.fkOwningWsID = Ws.pkWsID)
INNER JOIN [mnWorkstream_Leads] AS wsLeads ON Ws.pkWsID = wsLeads.fkWsID)
LEFT OUTER JOIN qryTrackerAllEeList AS company1 ON wsLeads.fkEeID = company1.Company1_ID)
LEFT OUTER JOIN qryTrackerAllEeList AS company2 ON wsLeads.fkEeID = company2.Company2_ID)
GROUP BY req.RequirementID, Ws.Wsnm