> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-mintlify-fbfa8bee.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# countIf

> countIf 组合器使用示例

<div id="description">
  ## 说明
</div>

[`If`](/zh/reference/functions/aggregate-functions/combinators#-if) 组合器可应用于 [`count`](/zh/reference/functions/aggregate-functions/count)
函数，使用 `countIf` 聚合组合器函数来统计条件为真的行数。

<div id="example-usage">
  ## 使用示例
</div>

在这个示例中，我们将创建一个用于存储用户登录尝试的表，
并使用 `countIf` 统计成功登录的次数。

```sql title="Query" theme={null}
CREATE TABLE login_attempts(
    user_id UInt32,
    timestamp DateTime,
    is_successful UInt8
) ENGINE = MergeTree
ORDER BY ();

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` 的行数。

```response title="Response" theme={null}
   ┌─user_id─┬─successful_logins─┐
1. │       1 │                 2 │
2. │       2 │                 2 │
   └─────────┴───────────────────┘
```

<div id="see-also">
  ## 另请参见
</div>

* [`count`](/zh/reference/functions/aggregate-functions/count)
* [`If 组合器`](/zh/reference/functions/aggregate-functions/combinators#-if)
