如何在单个查询中获取两个条件的多个SUM()

时间:2018-04-16 16:40:57

标签: c# sql ms-access

我在MS Access中有表:

Id | name  | code  |        ttime           | total | type  
-----------------------------------------------------------
1  | Abc   | 123   | 10-Feb-18 4:04:48 PM   | 2.01  | RS
2  | Abd   | 122   | 11-Feb-18 4:04:48 PM   | 3.90  | RS
3  | Abe   | 125   | 12-Feb-18 4:04:48 PM   | 23.00 | WS //other type
4  | Abf   | 124   | 13-Feb-18 4:04:48 PM   | 2.11  | RS
5  | Abg   | 126   | 13-Feb-18 5:04:48 PM   | 8.01  | WS // here too
6  | Abh   | 127   | 14-Feb-18 4:04:48 PM   | 5.01  | RS
7  | Abi   | 128   | 15-Feb-18 4:04:48 PM   | 9.10  | RS

我需要将第一列中仅总RS类型和第二列中WS类型总和的总和作为:

SELECT SUM(total) AS rstotal, 
       SUM(total) AS wstotal, 
       COUNT(code) 
WHERE ttime > '09-Feb-18 4:04:48 PM'

什么条件或自我加入会有所帮助?结果应该是这样的:

rstotal | wstotal | count
-------------------------
22.13   | 31.01   | 7

1 个答案:

答案 0 :(得分:5)

您可以使用条件聚合:

SELECT SUM(CASE WHEN type = 'RS' THEN total END) AS rstotal,
       SUM(CASE WHEN type = 'WS' THEN total END) AS wstotal,
       COUNT(code) AS "count"
FROM table1
WHERE ttime > '09-Feb-18 4:04:48 PM'

编辑正如史蒂夫指出的那样,MS Access不支持CASE WHEN,因此您必须使用IIf()功能:

SELECT SUM(IIf(type = 'RS', total, 0)) AS rstotal,
       SUM(IIf(type = 'WS', total, 0)) AS wstotal,
       COUNT(code) AS [count]
FROM table1
WHERE ttime > '09-Feb-18 4:04:48 PM'