sqlのcount使う方法と注意点

sqlでcount()を使用するときに、罠にはまってしまったので、書いておきます。

[ポイント]
複数の条件でのcount()の使い方
 →if文を利用する。条件に合致しなかったときはnullにする必要がある

たとえば、以下のようなテーブル(tables)があるとします。
f:id:harucharuru:20191220144829p:plain
f:id:harucharuru:20191220150643p:plain

一つの要素でのカウント

device_idごとの数を数える場合は、次のようなSQLを実行します。
 カウントした値を入れる要素はcountとする(count(`device_id`) as count )
 device_id順に並べる(order by `device_id`)
これは問題なくできました。

SELECT `device_id`,count(`device_id`) as count FROM `tables` group by `device_id` order by `device_id`

f:id:harucharuru:20191220145059p:plain

複数要素でのカウント

では、device_idごとにgender_idがそれぞれ0と1のものの値をカウントしてみましょう。
そこで以下のように実行してみると、、、

SELECT `device_id`,count(`gender_id`=0) as count0,count(`gender_id`=1) as count1 FROM `tables` group by `device_id` order by `device_id`

f:id:harucharuru:20191220145632p:plain
count(`gender_id`=0) as count0,count(`gender_id`=1) as count1としているのに、結果が同じになってしまいました。

どうやらif文を使う必要があるようなので、使ってみます。

SELECT `device_id`,count(if(`gender_id`=0,1,0)) as count0,count(if(`gender_id`=1,1,0)) as count1 FROM `tables` group by `device_id` order by `device_id`

f:id:harucharuru:20191220145632p:plain
それでも同じ結果になってしまいました。どうやら、if文で条件文に合致しなくても0としてしまうと、数としてカウントしてしまうみたいです。
そこで、0ではなくnullにしてみます。

SELECT `device_id`,count(if(`gender_id`=0,1,null)) as count0,count(if(`gender_id`=1,1,null)) as count1 FROM `tables` group by `device_id` order by `device_id`

f:id:harucharuru:20191220150746p:plain
できました!よかった!!!!