如何在同一个Query上使用不同的条件计算相同的字段

时间:2014-11-11 03:27:26

标签: sql vba ms-access

我有一个像这样的数据库

| Contact | Incident | OpenTime | Country | Product |
|    C1   |          | 1/1/2014 |   MX    |  Office |
|    C2   |    I1    | 2/2/2014 |   BR    |   SAP   |
|    C3   |          | 3/2/2014 |   US    |   SAP   |
|    C4   |    I2    | 3/3/2014 |   US    |   SAP   |
|    C5   |    I3    | 3/4/2014 |   US    |  Office |
|    C6   |          | 3/5/2014 |   TW    |   SAP   |

我想运行一个有关国家和开放时间标准的查询,我希望收到这样的内容:

| Product | Contacts with | Incidents |
|         | no Incidents  |           |
| Office  |      1        |     1     |
|   SAP   |      2        |     2     |

我可以轻松地使用像

这样的查询来完成一个部分
SELECT Service, count(
FROM database
WHERE criterias AND Incident is Null //(or Not Null) depending on the row
GROUP BY Product

我正在努力做的事情是计算事件是空的,并且事件在同一个表上并不是与上面示例中相同查询的结果。

我试过以下

SELECT Service AS Service,
(SELECT count Contacts FROM Database Where Incident Is Null) as Contact,
(SELECT count Contacts FROM Database Where Incident Is not Null) as Incident
FROM database
WHERE criterias AND Incident is Null //(or Not Null) depending on the row
GROUP BY Product

我对上面这句话的问题是,我在“主要”选择中使用的任何标准都被嵌套的选择忽略。

我也尝试过使用UNION ALL,但没有成功使用它。

最终我用这种方法解决了这个问题:我计算了每件产品的总联系人数,计算了事件数量,并添加了一个带有结果的计算字段

SELECT Service, COUNT (Contact) AS Total, COUNT (Incident) as Incidents, 
(Total - Incident) as Only Contact
From Database
Where <criterias>
GROUP BY Service

虽然我让它发挥作用,但我仍然确信它有更优雅的方法。 如何在一个查询中检索具有不同计数条件的同一列上的不同计数?

2 个答案:

答案 0 :(得分:3)

只需使用条件聚合:

SELECT Product,
       SUM(IIF(incident is not null, 1, 1)) as incidents,
       SUM(IIF(incident is null, 1, 1)) as noincidents
FROM database
WHERE criterias 
GROUP BY Product;

答案 1 :(得分:3)

可能非常适合MS Access解决方案:

TRANSFORM Count(tmp.Contact) AS CountOfContact
SELECT tmp.Product
FROM tmp
GROUP BY tmp.Product
PIVOT IIf(Trim([Incident] & "")="","No Incident","Incident");

这个IIf(Trim([Incident] & "")=""涵盖了Null字符串,Null和空格填充的所有可能性。

tmp是表的名称。