在SQL中连接三个表和两个子查询

时间:2014-07-08 17:24:52

标签: sql ms-access

我有一个有点疯狂的查询,需要来自4个表的信息。它们全部连接在GRANTS表上,另外3个我需要运行总和。 T1是一个表格,可以让我访问来自不同表格的两个数字的乘积之和。 T2是一个表格,可以让我访问该表格中一个项目的总和。然后,我需要对所有这些值进行基本数学运算,再加上GRANTS表中的值,以便给出结果。

以下是我的查询:

SELECT GRANTS.[Grant Program Number],
         ( GRANTS.[Grant Request]
           - IIF(T2.CRM is Null, 0, T2.CRM)
         )
       - ( IIF(T1.EDC Is Null,0,T1.EDC)
           + GRANTS.Overhead
         ) AS [Net Net Request]
FROM       ( SELECT RESOURCES.[Grant Program Number] AS GPN,
                    Sum( RESOURCES.[Hours Spent]
                           * EMPLOYEES.[Employee Rate]
                    ) AS EDC
             FROM EMPLOYEES
             INNER JOIN RESOURCES ON EMPLOYEES.[Employee Number] = RESOURCES.[Employee Number] 
             GROUP BY RESOURCES.[Grant Program Number]
           )  AS T1
RIGHT JOIN GRANTS ON T1.GPN = GRANTS.[Grant Program Number] 
LEFT JOIN  ( SELECT COLLABORATORS.[Grant Program Number] AS GPN,
             Sum(COLLABORATORS.[Request Made]) AS CRM
             FROM COLLABORATORS 
             GROUP BY COLLABORATORS.[Grant Program Number]
           ) AS T2 ON GRANTS.[Grant Program Number] = T2.GPN
WHERE GRANTS.[Grant Submitted] = Yes
  AND GRANTS.[Submission Date] >= Forms!StartDate!Text0
  AND GRANTS.[Submission Date] <= DateAdd("m",+12,Forms!StartDate!Text0)
;

如果我删除主要SELECT中T1和T1中引用的SELECT值,它就可以工作。如果我删除T2并保留T1也是如此。但是当他们在一起时,我会在连接3个表的大型FROM语句上得到Syntax error (missing operator)

感谢。

1 个答案:

答案 0 :(得分:0)

我忘记了将3个表连接在一起时,必须关闭括号中的第一个连接。我粗略地说:

Table1 RIGHT JOIN Table2 LEFT JOIN Table3

我需要的地方

(Table1 RIGHT JOIN Table2) LEFT JOIN Table3