查询数据库中特定项的数量

时间:2013-01-03 07:13:42

标签: sql ms-access

我只是想知道如何计算特定设备的数量..

SELECT 
    EQUIPMENTS.DESCRIPTION AS [EQUIPMENT TYPE], 
    Count(EQUIPMENTS.EQNAME) AS QUANTITY,
    (SELECT Count(EQUIPMENTS.CONDITION) FROM EQUIPMENTS WHERE EQUIPMENTS.CONDITION = 'Functional') AS WORKING,
    (SELECT Count(EQUIPMENTS.CONDITION) FROM EQUIPMENTS WHERE EQUIPMENTS.CONDITION = 'Non-Functional') AS [NON-WORKING]
FROM EQUIPMENTS
GROUP BY EQUIPMENTS.DESCRIPTION;

此查询返回以下内容:

EQUIPMENT NAME : PROJECTOR
QUANTITY : 3
WORKING : 2
NON-WORKING :1

现在,如果我添加另一种具有不同类型的设备,例如CALCULATOR,它将具有相同的工作和非工作计数,仅适用于PROJECTOR。我该如何计算计算器的数量以及工作和非工作的数量?我的意思是每当我添加另一个具有特定描述的设备时,查询也会独立计算它?

我正在使用VB.NET,此查询是在MS ACCESS 2007中进行的。

1 个答案:

答案 0 :(得分:1)

使用IIf()表达式在条件满足时返回1,在不满足时返回0。然后Sum这些值。

SELECT 
    e.DESCRIPTION AS [EQUIPMENT TYPE], 
    Count(e.EQNAME) AS QUANTITY,
    Sum(IIf(e.CONDITION = 'Functional', 1, 0)) AS WORKING,
    Sum(IIf(e.CONDITION = 'Non-Functional', 1, 0)) AS [NON-WORKING]
FROM EQUIPMENTS AS e
GROUP BY e.DESCRIPTION;