计算MS-Access中同一字段中的两种值

时间:2011-04-24 12:58:02

标签: sql tsql ms-access ms-access-2007

我有这个表customerDetail,其中有一个字段c_type,其中“a”表示“active”而“d”表示“not-active”。现在我必须在同一个查询中找到它们的计数 我用过这些但没有结果。

SELECT Count(c_type) AS Active, Count(c_type) AS Not_Active  
FROM customerDetail  
WHERE c_type="a" OR c_type="d"

当然我知道它看起来很脏,但我也试过这个,但这也没用 -

SELECT
    Count(customerDetail.c_type) AS Active,
    Count(customerDetail_1.c_type) AS Not_Active  
FROM customerDetail INNER JOIN customerDetail AS customerDetail_1  
ON customerDetail.Id=customerDetail_1.Id  
WHERE (customerDetail.c_type="a") AND (customerDetail_1.c_type="d")

但是它也没有帮助,所以有人可以告诉我,我应该如何知道同一查询中活动和非活动的数量?

3 个答案:

答案 0 :(得分:5)

select c_type, count(*)
from customer_detail
group by c_type

答案 1 :(得分:4)

SELECT
  SUM(IIF(c_type = "a", 1, 0)) AS Active,
  SUM(IIF(c_type = "d", 1, 0)) AS Not_Active,
FROM customerDetail
WHERE c_type IN ("a", "d")

那是MS Access。

第一次看到这个问题时,我错过了tsql标签。在Transact-SQL中,您可以使用CASE构造,可以将其视为Access中IIF的更强大的等价物:

SELECT
  SUM(CASE c_type WHEN 'a' THEN 1 ELSE 0 END) AS Active,
  SUM(CASE c_type WHEN 'd' THEN 1 ELSE 0 END) AS Not_Active,
FROM customerDetail
WHERE c_type IN ('a', 'd')

实际上,在T-SQL中我会使用COUNT而不是SUM,如下所示:

SELECT
  COUNT(CASE c_type WHEN 'a' THEN 1 END) AS Active,
  COUNT(CASE c_type WHEN 'd' THEN 1 END) AS Not_Active,
FROM customerDetail
WHERE c_type IN ('a', 'd')

每个CASE表达式中的1可以被任何东西替换,只要它不是NULL(不计算NULL)。如果省略了ELSE部分,就像上面的查询一样,隐含了ELSE NULL

答案 2 :(得分:1)

这里的挑战是你的要求,“在同一个查询中”。

创建单独的查询会很容易。

qryActive:

SELECT Count(*) AS Active
FROM customerDetail
WHERE c_type="a"

qryInactive:

SELECT Count(*) AS Not_Active
FROM customerDetail
WHERE c_type="d"

如果你需要一个,你可以将它们作为子查询合并。

SELECT a.Active, i.Not_Active
FROM
    (SELECT Count(*) AS Active
    FROM customerDetail
    WHERE c_type="a") AS a,
    (SELECT Count(*) AS Not_Active
    FROM customerDetail
    WHERE c_type="d") AS i

如果没有JOIN或WHERE条件,您将获得两个子查询的“交叉连接”(笛卡尔积)。但是,由于每个子查询只生成一行,因此复合只包含一行。