简体   繁体   English

具有分组依据和条件的MS Access Union查询

[英]MS Access Union Query with group by and criteria

I have the following query and need to do a union with another table which has the exact same fields. 我有以下查询,并且需要与另一个具有完全相同字段的表进行联合。 The criteria, however, could span information in both tables. 但是,该标准可以涵盖两个表中的信息。

Any ideas on how to do the union with the group by and criteria? 关于如何与小组成员和准则进行合并的任何想法?

SELECT sporderpipeline.coordinator, 
       sporderpipeline.[update date], 
       Count(sporderpipeline.loan_number) AS CountOfLoan_Number, 
       sporderpipeline.[data source] 
FROM   sporderpipeline 
GROUP  BY sporderpipeline.coordinator, 
          sporderpipeline.[update date], 
          sporderpipeline.status, 
          sporderpipeline.[data source] 
HAVING ( ( ( sporderpipeline.[update date] ) BETWEEN #8/23/2015# AND #8/24/2015# 
         ) 
         AND ( ( sporderpipeline.status ) IS NOT NULL ) ); 

You don't need to use a HAVING clause for those criteria - HAVING is only necessary for criteria based on aggregate functions such as COUNT or SUM. 您不需要为这些条件使用HAVING子句HAVING仅对于基于诸如COUNT或SUM之类的聚合函数的条件是必需的。

The simplest way to write your UNION query is as follows: 编写UNION查询的最简单方法如下:

SELECT [sporderpipeline].[coordinator], 
       [sporderpipeline].[update date], 
       Count([sporderpipeline].[loan_number]) AS CountOfLoan_Number, 
       [sporderpipeline].[data source] 
FROM   sporderpipeline 
WHERE  [update date] BETWEEN #8/23/2015# AND #8/24/2015# 
       AND status IS NOT NULL 
GROUP  BY [sporderpipeline].[coordinator], 
          [sporderpipeline].[update date], 
          [sporderpipeline].[status], 
          [sporderpipeline].[data source] 
UNION 
SELECT [sporderpipeline].[coordinator], 
       [sporderpipeline].[update date], 
       Count([sporderpipeline].[loan_number]) AS CountOfLoan_Number, 
       [sporderpipeline].[data source] 
FROM   sporderpipeline 
WHERE  [update date] BETWEEN #8/23/2015# AND #8/24/2015# 
       AND status IS NOT NULL 
GROUP  BY [sporderpipeline].[coordinator], 
          [sporderpipeline].[update date], 
          [sporderpipeline].[status], 
          [sporderpipeline].[data source] 

Having said that, it would also work with a HAVING clause, which is not incompatible with a UNION. 话虽如此,它也可以与不与UNION不兼容的HAVING子句一起使用。

Create the companion query. 创建伴随查询。 We'll call it MyQuery_Second . 我们将其称为MyQuery_Second

SELECT * FROM MyQuery_First UNION SELECT * FROM MyQuery_Second;

... or possibly even ... ...甚至可能...

MyQuery_First UNION MyQuery_Second;

It should just work. 它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM