Question

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.

Was it helpful?

Solution

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))

OTHER TIPS

Use GROUP BY instead of IIF. Try this:

SELECT [Division:], [Category], Count([Category]) AS Category_Count
FROM tblAssssDB
GROUP BY [Division:], [Category];

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

Select count(iif(fieldname='a',1,null)) as  asde 
from [table name] 
where .....
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top