Help us understand the problem. What is going on with this article?

SQLでCOUNTIF

More than 1 year has passed since last update.

ExcelのCOUNTIF関数は、条件に一致する件数をカウントする便利関数。

=COUNTIF(A1:A3, "Apple")

みたいなの。
これをSQLでやる場合、SUMとCASEを組み合わせてやる。
CASE使って、条件に一致する場合1、しない場合0としてやってその合計をSUMで出す。

COLA
Apple
Orange
Apple

例えば上の表TBLAからCOLA=Appleの件数を抽出する場合、下記で出す。

SELECT
SUM(CASE WHEN COLA='Apple' THEN 1 ELSE 0 END) AS CNT
FROM TBLA;

CNT
2

・・・
ツッコんだ人も多いと思うけど、この要件ならこんなことしなくてもWHEREで条件入れてCOUNTとれば事足りる。

SELECT COUNT(*) AS CNT FROM TBLA WHERE COLA='Apple';

わざわざSUMとCASE使うメリットはWHEREを使わないということぐらい。
なので、異なる条件の件数を同時に取得したい、って場合に使える。
例えば全件数とCOLA=Appleの件数を1回のSQLで同時に取得したい場合、

SELECT
COUNT(*) AS ALL_CNT
,SUM(CASE WHEN COLA='Apple' THEN 1 ELSE 0 END) AS APPLE_CNT
FROM TBLA;

ALL_CNT APPLE_CNT
3 2

わりとSUMとCASEを組み合わせることで、1回のSQLで色々取得することが出来るようになるので便利。

※ DB2 10で確認しました

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away