有点复杂的内连接和求和查询

时间:2013-01-17 14:12:56

标签: sql ms-access count inner-join

我遇到了一个问题,如果你们能帮助我,我会很感激。

我们使用表格(MS Access)为多家公司存储项目计划,如下所示:

ID    PROJECT_NAME   COMPANY_NAME   MILESTONE_NAME   MILESTONE_TYPE

我的查询目标是返回“适用”部署的计数。

推出是项目和公司的独特组合。例如:

Project 1 being executed in the Company A
Project 2 being executed in the Company A
Project 1 being executed in the Company B

适用的项目是其最后里程碑的MILESTONE_TYPE与“DUMMY”不同的任何项目。

适用的推出应如下所示:

ID    PROJECT_NAME   COMPANY_NAME   MILESTONE_NAME           MILESTONE_TYPE
1     Project 3      Company D      6.2 Rollout Completed    Applicable

为了检索项目的最后一个里程碑,我使用以下SQL:

SELECT Sheet1.[PROJECT_NAME], MAX(Sheet1.[MILESTONE_NAME])
FROM Sheet1
    INNER JOIN Sheet1 AS Sheet1_1 ON (Sheet1.[PROJECT_NAME] = Sheet1_1.[PROJECT_NAME])
        AND (Sheet1.[MILESTONE_NAME] = Sheet1_1.[MILESTONE_NAME])
GROUP BY Sheet1.[PROJECT_NAME]
ORDER BY Sheet1.[PROJECT_NAME]

我需要您支持的查询的预期结果是:

PROJECT_NAME  COUNT_OF_APPLICABLE_ROLLOUTS
Project A     5
Project B     6

但是我完全不知道怎么开始...... 有谁知道如何在SQL查询中输入所有内容?

提前致谢。

2 个答案:

答案 0 :(得分:0)

假设较大的“id”意味着稍后,以下查询返回有关最新非虚拟行的信息:

select p.*
from Sheet1.p join
     (select project_name, company_name, max(id) as maxid
      from Sheet1
      where Milestone_Name <> 'Dummy'
      group by project_name, company_name
     ) pc
     on p.project_name, pc.company_name

(注意:我没有对此进行测试,因此可能存在语法错误。)

答案 1 :(得分:0)

你可以试试这个:

    SELECT  myTable.*
FROM    (
        SELECT  DISTINCT COMPANY_NAME
        FROM    Sheet1
        ) CN
CROSS APPLY
        (
        SELECT  TOP 1 *
        FROM    Sheet1 myTable2
        WHERE   myTable2.COMPANY_NAME = CN.COMPANY_NAME
        ORDER BY
                MILESTONE_NAME DESC
        ) myTable