KimNR
KimNR

Reputation: 27

MySQL - group by for counting except null

I'm trying to make a chart for my board. But I have no idea how I can count the number of the article_id only if it is not null.

In the below, if article_id is null, it should not be counted. How can I fix this?

mysql> select article_id, count(*) as count from board group by article_id order by count desc limit 3;
+------------+-------+
| article_id | count |
+------------+-------+
|       NULL |     7 |
|         12 |     3 |
|          3 |     2 |
+------------+-------+
3 rows in set (0.00 sec)

Upvotes: 1

Views: 191

Answers (3)

Sh Ndrukaj
Sh Ndrukaj

Reputation: 84

you should try mysql> select article_id, count(*) as count from board group by article_id where article_is is not null order by count desc limit 3;

Upvotes: 1

Luis Da Silva
Luis Da Silva

Reputation: 85

select article_id, count(*) as count 
from board 
where  
article_id is not null
group by article_id 
order by count desc limit 3

Upvotes: 3

Josh J
Josh J

Reputation: 6893

Filter out nulls with a WHERE article_id IS NOT NULL

Upvotes: 3

Related Questions