1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

値がNULLのレコードをCOUNT集計をしてくれなかった件

Posted at

##やりたかったこと
カラムの値別のレコード件数を知りたい

##データ

id pref_id
100000 27
138659 NULL
200000 13
262241 NULL
268371 NULL
269365 NULL
300000 13

##期待していた結果

pref_id cnt
13 2
27 1
NULL 4

##ここで、つまづいた

mysql> select pref_id, count(pref_id) as cnt from dtb_customer group by pref_id;
+---------+-------+
| pref_id | cnt   |
+---------+-------+
|      13 |     2 |
|      27 |     1 |
|    NULL |     0 |

カラムの値がNULLであるレコード件数がゼロで返ってきた

##解決

mysql> select pref_id, count(*) as cnt from dtb_customer group by pref_id;
+---------+-------+
| pref_id | cnt   |
+---------+-------+
|      13 |     2 |
|      27 |     1 |
|    NULL |     4 |

集計関数countにカラムを指定せず、レコード全体を指定すると
NULLレコードをカウントしてくれた

##環境
MySQL 5.7.27

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?