IIf statement including count and query aggregate error

Hello,

I am trying to run a query that includes an if statement with an aggregate function. The goal is to count the number of women in the table if the pwbox =2. If the pwbox is not 2, I want the query to return "0", not null.

When I execute the SQL statement below, I get the error message "you tried to execute a query that does not include the specific expression..."

How can I rewrite the query? I see that the problem is related to categorizing my IIf statement as an expression rather than in the group by clause, but I'm not sure how to fix it. I am not an advanced SQL user, so please keep that in mind.

SELECT TBADataForm.year, TBADataForm.term, IIf([pwbox]<>"2","0",Count([womanname])) AS [maternal death tba]
FROM TBADataForm
GROUP BY TBADataForm.year, TBADataForm.term, IIf([pwbox]<>"2","0",Count([womanname]));

JTT
ghaphisAsked:
Who is Participating?
 
ThomasianConnect With a Mentor Commented:
Is this what you wanted?

SELECT TBADataForm.year, TBADataForm.term, Count(IIf([pwbox]="2",[womanname])) AS [maternal death tba]
FROM TBADataForm
GROUP BY TBADataForm.year, TBADataForm.term
0
 
k_murli_krishnaCommented:
Correction:

SELECT TBADataForm.year, TBADataForm.term, Count(IIf([pwbox]="2",[womanname],"0")) AS [maternal death tba]
FROM TBADataForm
GROUP BY TBADataForm.year, TBADataForm.term;

OR

SELECT TBADataForm.year, TBADataForm.term, Count(IIf([pwbox]<>"2","0",[womanname])) AS [maternal death tba]
FROM TBADataForm
GROUP BY TBADataForm.year, TBADataForm.term;

You can use single quotes instead of ". That is in SQL. In Java etc. it is treated as String and hence ".
0
 
ThomasianCommented:
k_murli_kris…,

Was the correction for my query? The 2nd parameter of the IIF function is optional. If it is not supplied, NULL is returned. And if you want to put an "else" value, you should use NULL instead of "0". COUNT function includes all non-null values in the count.
0
All Courses

From novice to tech pro — start learning today.