31
33

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 5 years have passed since last update.

【SQL】複数の条件のcountを1回のクエリでおこなう

Posted at

参考:【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できる。

31
33
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
31
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?