Search code examples
sqlms-accesscountiif

Count + IIF - Access query


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.


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