Count + IIF - Access query

三世轮回 提交于 2019-12-08 08:13:02

问题


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.


回答1:


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



回答2:


Use GROUP BY instead of IIF. Try this:

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



回答3:


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:


Select count(iif(fieldname='a',1,null)) as  asde 
from [table name] 
where .....


来源:https://stackoverflow.com/questions/22990229/count-iif-access-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!