在一个查询/表

时间:2016-01-13 16:51:32

标签: sql ms-access

我有四个相同字段的表(地理位置,q1,q2,q3,q4)。我需要找到四个表中每个表的四分之一的总和,并生成一个新表,其中包括地理位置,表1的总和,表2的总和,表3的总和,表4的总和。

我可以单独得到每个总和,但无法弄清楚如何将它们组合成一个表。下面是一个表的工作代码,A:

SELECT [A].Geography, 
       Sum([A].[q1])+Sum([A].[q2])+Sum([A].[q3])+Sum([A].[q4]) AS TSUM
FROM [A]
GROUP BY [A].Geography
ORDER BY [A].Geography;

1 个答案:

答案 0 :(得分:0)

只需按Geography加入所有表,检索其汇总列总和。下面假设所有表中的所有地理位置都相同,表A作为匹配源:

SELECT [A].Geography, 
       Sum([A].[q1])+Sum([A].[q2])+Sum([A].[q3])+Sum([A].[q4]) AS TSUM_A,
       Sum([B].[q1])+Sum([B].[q2])+Sum([B].[q3])+Sum([B].[q4]) AS TSUM_B,
       Sum([C].[q1])+Sum([C].[q2])+Sum([C].[q3])+Sum([C].[q4]) AS TSUM_C,
       Sum([D].[q1])+Sum([D].[q2])+Sum([D].[q3])+Sum([D].[q4]) AS TSUM_D

FROM (([A] 
INNER JOIN [B] ON [A].Geography = [B].Geography) 
INNER JOIN [C] ON [A].Geography = [C].Geography) 
INNER JOIN [D] ON [A].Geography = [D].Geography

GROUP BY [A].Geography
ORDER BY [A].Geography;

如果地理位置在所有四个表中都不同,请考虑此解决方法,使用所有表中所有地理位置的派生表联合查询(UNION返回不同的值与UNION ALL)然后LEFT JOINs所有表格,AD。当然,这个不同地理记录的派生表可以是在FROM子句中相同位置引用的已保存的Access查询。请注意,在此方法中,NULL值将出现在地理位置未显示在特定表中的行中。

SELECT main.Geography, 
       Sum([A].[q1])+Sum([A].[q2])+Sum([A].[q3])+Sum([A].[q4]) AS TSUM_A,
       Sum([B].[q1])+Sum([B].[q2])+Sum([B].[q3])+Sum([B].[q4]) AS TSUM_B,
       Sum([C].[q1])+Sum([C].[q2])+Sum([C].[q3])+Sum([C].[q4]) AS TSUM_C,
       Sum([D].[q1])+Sum([D].[q2])+Sum([D].[q3])+Sum([D].[q4]) AS TSUM_D

FROM (((     
       (SELECT Geography FROM A 
        UNION SELECT Geography FROM B 
        UNION SELECT Geography FROM C
        UNION SELECT Geography FROM D) As main

LEFT JOIN [A] ON [main].Geography = [A].Geography)
LEFT JOIN [B] ON [main].Geography = [B].Geography) 
LEFT JOIN [C] ON [main].Geography = [C].Geography) 
LEFT JOIN [D] ON [main].Geography = [D].Geography

GROUP BY [main].Geography
ORDER BY [main].Geography;

注意处理连接子句中的括号,因为MS Access SQL需要这些括号。