简体   繁体   中英

SQL: Incorrect count on Null column

MySQL SQL is not returning the correct count for records that have null and not null values

I have the following values in a table with three columns (code,amt,name)

"AMPF";"0.1000";"Amplify Inc";
"AMPF";"0.1000";"Amplify Inc";
"AMPF";"0.2000";"Amplify Inc";
"AMPF";"0.2000";"Amplify Inc";
"AMPF";"0.3000";"Amplify Inc";
"AMPF";"0.3000";"";
"AMPF";"0.4000";"";
"XYZA";"0.1000";"PeterPal Inc";
"XYZA";"0.1000";"PeterPal Inc"

I am running the following query to pick up the number of records that exist for a particular item code. SELECT code, name, count(amt) as cnt FROM table group by code order by cnt desc limit 30

SELECT code, name, count(amt) as cnt FROM table group by code order by cnt desc limit 30

Ideally, the expected result should be:

AMPF,Amplify Inc,7
XYZA,PeterPal Inc,2

But instead, it is resulting in:

AMPF,Amplify Inc,5
XYZA,PeterPal Inc,2

It indicates that although I am taking the count on amt column, it is somehow taking it on name column which is null in record numbers 6 and 7. Any thoughts on what is going wrong in my code?

First, just use count(*) :

SELECT code, MAX(name) as name, count(*) as cnt
FROM table 
GROUP BY code 
ORDER BY cnt desc 
LIMIT 30;

What is happening is that the values that look like 'AMPF' are not really 'AMPF' -- that is, they are not equal. I don't know why. It could be spaces at the beginning of the code, it could be "look-alike" characters in different character sets, it could be hidden characters.

If you look further down the list, you should see the other codes being counted -- if you leave out the LIMIT .

I also changed the SELECT so NAME is not taken from an indeterminate row. This simply uses the MAX() value found.

Unfortunately, this condition does not have a straightforward answer. By design, MySQL count() function actually counts ONLY the NOT NULL values. However, there are the following two workarounds that can be implemented:

First, One can run a separate SQL statement to count the records which are NULL.

Second, if one (or more) of the desired values are available in another table through a foreign key, pick up those values from the other table, and run a count on first table to get the correct count.

PS: I used the first one for my needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM