Count + IIF - Access query

2019-05-31 13:33发布

Employees of the company are divided into categories A, B and C regardless of the division they work in (Finance, HR, Sales...)

How can I write a query (Access 2010) in order to retrieve the number of employees for each category and each division?

The final output will be an excel sheet where the company divisions will be in column A, Category A in column B, category B in column and category C in column D.

I thought an IIF() nested in a COUNT() would do the job but it actually counts the total number of employees instead of giving the breakdown by category.

Any idea?

SELECT
    tblAssssDB.[Division:],
    COUNT( IIF( [Category]   = "A", 1, 0 ) ) AS Count_A,
    COUNT( IIF( [Category]   = "B", 1, 0 ) ) AS Count_B,
    COUNT( IIF( [ET Outcome] = "C", 1, 0 ) ) AS Count_C
FROM
    tblAssssDB
GROUP BY
    tblAssssDB.[Division:];

My aim is to code a single sql statement and avoid writing sub-queries in order to calculate the values for each division.

4条回答
可以哭但决不认输i
2楼-- · 2019-05-31 13:40
Select count(iif(fieldname='a',1,null)) as  asde 
from [table name] 
where .....
查看更多
我想做一个坏孩纸
3楼-- · 2019-05-31 13:46

Try this Count:

Count(IIf([Field1]="N",1))+Count(IIf([Field2]="N",1)) ...

I grouped my qry and place Expression under this Count field I created. It worked for me

查看更多
唯我独甜
4楼-- · 2019-05-31 13:54

Count counts every non-Null value ... so you're counting 1 for each row regardless of the [Category] value.

If you want to stick with Count ...

Count(IIf([Category]="A",1,Null))

Otherwise switch to Sum ...

Sum(IIf([Category]="A",1,0))
查看更多
Luminary・发光体
5楼-- · 2019-05-31 13:54

Use GROUP BY instead of IIF. Try this:

SELECT [Division:], [Category], Count([Category]) AS Category_Count
FROM tblAssssDB
GROUP BY [Division:], [Category];
查看更多
登录 后发表回答