使用GROUP BY SUM两个SELECT COUNT查询

时间:2012-11-28 18:33:16

标签: sql ms-access

我在链接数据库中有两个查询(链接来自两个不同项目数据库的表)。我需要组合查询以获得按Interaction_Type1分组的总计数。 SQL代码如下:

查询#1:

SELECT Sum(Temp.cnt) AS SumOfcnt, Temp.Interaction_Type1
FROM (SELECT COUNT(*) as cnt, Interaction_Type1 from AMERILOCKMasterConversionTable 
GROUP BY Interaction_Type1

UNION ALL

SELECT COUNT(*), Interaction_Type2 from AMERILOCKMasterConversionTable
GROUP BY Interaction_Type2

UNION ALL

SELECT COUNT(*), Interaction_Type3 from AMERILOCKMasterConversionTable
GROUP BY Interaction_Type3
)  AS Temp
GROUP BY Temp.Interaction_Type1;

和查询#2

SELECT Sum(Temp.cnt) AS SumOfcnt, Temp.Interaction_Type1
FROM (SELECT COUNT(*) as cnt, Interaction_Type1 from MARKETMasterConversionTable 
GROUP BY Interaction_Type1

UNION ALL

SELECT COUNT(*), Interaction_Type2 from MARKETMasterConversionTable 
GROUP BY Interaction_Type2

UNION ALL

SELECT COUNT(*), Interaction_Type3 from MARKETMasterConversionTable 
GROUP BY Interaction_Type3
)  AS Temp
GROUP BY Temp.Interaction_Type1;

我希望查询得出以下结果:

Interaction_Type1          Total
Left_Message                23
Made_Contact                16
Bad_Phone_Number             8
No_Answer                   12

我是SQL的新手,并且已经在线研究了所有这些内容,并且没有把这两个查询结合起来以产生预期结果。

任何帮助都会非常感激!!

谢谢! 红色

1 个答案:

答案 0 :(得分:1)

你应该有像

这样的东西
SELECT  Integration_Type, SUM(*)
FROM    (  SELECT Integration_Type, SumOfcnt FROM VIEW1
           UNION ALL
           SELECT Integration_Type, SumOfcnt FROM VIEW2)
GROUP BY Integration_Type

但在为此处提供的查询创建视图之前,或者只是在单个视图中收集所有查询。