参考:【SQL】複数の条件のcountを1回のクエリでおこなう
hogeテーブル
| id | status |
|---|---|
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
| 4 | 2 |
| 5 | 0 |
| 6 | 2 |
| 7 | 0 |
| 8 | 1 |
statusが0の件数、statusが1か2の件数。
これをひとつのSQLでcountする。
select
count(status = 0 or null), --statusが0の件数
count(status in(1,2) or null) --statusが1か2の件数
from
hoge
これでできてしまう。すごい!
解説
count(*)は全件、count(*以外)はnull以外をcountする。
ゆえに条件に合致するものをtrue,合致しないものをnullで返す。
true or null ->true -> countされる。
false or null ->null -> countされない。
ゆえに、count(条件 or null)で条件でcountできる。