メインコンテンツまでスキップ
メインコンテンツまでスキップ

countIf

説明

If コンビネーターは、count 関数に適用することができ、countIf 集約コンビネーター関数を使用して、条件が真である行の数をカウントします。

使用例

この例では、ユーザーログイン試行を保存するテーブルを作成し、countIf を使用して成功したログインの数をカウントします。

CREATE TABLE login_attempts(
    user_id UInt32,
    timestamp DateTime,
    is_successful UInt8
) ENGINE = Log;

INSERT INTO login_attempts VALUES
    (1, '2024-01-01 10:00:00', 1),
    (1, '2024-01-01 10:05:00', 0),
    (1, '2024-01-01 10:10:00', 1),
    (2, '2024-01-01 11:00:00', 1),
    (2, '2024-01-01 11:05:00', 1),
    (2, '2024-01-01 11:10:00', 0);

SELECT
    user_id,
    countIf(is_successful = 1) AS successful_logins
FROM login_attempts
GROUP BY user_id;

countIf 関数は、各ユーザーについて is_successful = 1 の行のみをカウントします。

   ┌─user_id─┬─successful_logins─┐
1. │       1 │                 2 │
2. │       2 │                 2 │
   └─────────┴───────────────────┘

その他