1

I my following query, the last column returns the count of the instances, for this instances with 0 count I would like to replace them with 'N/A'?

This query does not seems to work

select m.id, m.desc, count(IF(i.id is NULL,'N/A',i.id)) as quant
from menu m left join items i
on m.id = i.id
group by m.id
order by m.id;

The above query outputs as

============================
m.id     |c.desc     | qaunt
============================
1234     | Shoes     | 1
1235     | Socks     | 2
1236     | Clothes   | 0
===========================

Expected result:

============================
m.id     |m.desc     | qaunt
============================
1234     | Shoes     | 1
1235     | Socks     | 2
1236     | Clothes   | N/A
===========================

Could you please suggest me the changes in the above query

4

4 回答 4

3

(This is tested) Your query is counting the results of the if, and I think you want the inverse. I am using a pairing of IFNULL and NULLIF, which together say "if the count is zero, translate that to NULL. Then if it's NULL, use "N/A" for this column.

select m.id, m.desc, 
IFNULL(NULLIF(count(i.id), 0), "N/A") as quant
from menu m left join items i
on m.id = i.id
group by m.id
order by m.id;

To be pedantic for mysql, you can ensure that the column is always a string via cast():

IFNULL(NULLIF(CAST(count(i.id) AS char), "0"), "N/A") as quant

This has the benefit of only counting once and no subquery.

于 2012-11-01T21:13:48.853 回答
2

can you try

select m.id, m.desc, if(count(i.id) = 0,'N/A',count(i.id))) as quant
from menu m left join items i
on m.id = i.id
group by m.id
order by m.id;
于 2012-11-01T21:11:58.480 回答
0

NULL & 0 are not the same

select m.id, m.desc, count(IF(i.id = 0,'N/A',i.id)) as quant
from menu m left join items i
on m.id = i.id
group by m.id
order by m.id;
于 2012-11-01T21:15:07.927 回答
0

FOR MSSQL or TSQL change IFNULL with ISNULL and double quotes " with single quote '.

select m.id, m.desc, 
ISNULL(NULLIF(count(i.id), 0),'N/A') as quant
from menu m left join items i
on m.id = i.id
group by m.id
order by m.id;

于 2021-12-09T11:52:03.143 回答