ProjectId的组名

时间:2017-12-13 17:44:00

标签: sql ms-access

我在下面有一个表格,我需要在MS Access查询

中对名称进行分组
ProjectID  ProjectMgr  PortfolioMgr  
1103       John Smith  
1103                   Jane Doe  
1104       John Smith  
1104                   Tom White  

我需要忽略空值并将其分组为

ProjectID ProjectMgr  PortfolioMgr  
1103      John Smith  Jane Doe  
1104      John Smith  Tom White  

我尝试了一个组查询,但不确定在两列的表达式中使用什么。

Select ProjectID, ProjectMgr, PortfolioMgr 
from tblProjectAssignment 
group by ProjectID

Access给我错误:

  

您的查询不包含指定的表达式ProjectMgr,   PortfolioMgr作为聚合函数的一部分。

任何帮助表示感谢。

3 个答案:

答案 0 :(得分:0)

您可以尝试使用GROUP BY子句选择所有不同的项目ID,然后使用子查询来获取项目经理和项目组合经理。

SELECT a.ProjectID, 
(SELECT s1.ProjectMgr FROM MyTable s1 WHERE s1.ProjectID = a.ProjectID and s1.ProjectMgr Is Not Null) As ProjectMgr, 
(SELECT s2.PortfolioMgr FROM MyTable s2 WHERE s2.ProjectID = a.ProjectID and s2.PortfolioMgr Is Not Null) As PortfolioMgr 
FROM (
   SELECT ProjectID From MyTable GROUP BY ProjectID
) As a

您需要将MyTable替换为您的表名

请注意,当每个ID有多个项目/项目组合经理时,此查询将失败

或者,您可以使用连接并将表连接3次:

SELECT a.ProjectID, b.ProjectMgr, c.PortfolioMgr
FROM (SELECT ProjectID From MyTable GROUP BY ProjectID) a
INNER JOIN (SELECT ProjectID, ProjectMgr From MyTable WHERE ProjectMgr Is Not Null) b ON a.ProjectID = b.ProjectID
INNER JOIN (SELECT ProjectID, PortfolioMgr From MyTable WHERE PortfolioMgr Is Not Null) c ON a.ProjectID = c.ProjectID

答案 1 :(得分:0)

您可以使用此代码

SELECT a.ProjectID, b.ProjectMgr, c.PortfolioMgr
FROM Your_Table_Name a
INNER JOIN (SELECT ProjectID, ProjectMgr From Your_Table_Name b WHERE ProjectMgr Is Not Null) b ON a.ProjectID = b.ProjectID
INNER JOIN (SELECT ProjectID, PortfolioMgr From Your_Table_Name c WHERE PortfolioMgr Is Not Null) c ON a.ProjectID = c.ProjectID
GROUP BY a.ProjectID

答案 2 :(得分:0)

只需使用MAX()聚合:

SELECT ProjectID, MAX(ProjectMgr) As Project_Manager,
                  MAX(PortfolioMgr) AS Portfolio_Manager
FROM myTable
GROUP BY ProjectID