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

# uniqArrayIf

> uniqArrayIf 组合器使用示例

<div id="description">
  ## 描述
</div>

可以将 [`Array`](/zh/reference/functions/aggregate-functions/combinators#-array) 和 [`If`](/zh/reference/functions/aggregate-functions/combinators#-if) 组合器应用于 [`uniq`](/zh/reference/functions/aggregate-functions/uniq)
函数，使用 `uniqArrayIf` 聚合组合器函数统计条件为真的
行中数组内唯一值的数量。

<Note>
  -`If` 和 -`Array` 可以组合使用。不过，`Array` 必须在前，`If` 在后。
</Note>

当你想基于特定条件统计数组中的唯一元素，又不想使用 `arrayJoin` 时，
这会非常有用。

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

<div id="count-unique-products">
  ### 按细分类型和参与度级别统计浏览过的唯一产品数
</div>

在本示例中，我们将使用一张包含用户购物会话数据的表，统计特定用户细分中、
以会话停留时间作为参与度指标的用户所浏览过的唯一产品数量。

```sql title="Query" theme={null}
CREATE TABLE user_shopping_sessions
(
    session_date Date,
    user_segment String,
    viewed_products Array(String),
    session_duration_minutes Int32
) ENGINE = Memory;

INSERT INTO user_shopping_sessions VALUES
    ('2024-01-01', 'new_customer', ['smartphone_x', 'headphones_y', 'smartphone_x'], 12),
    ('2024-01-01', 'returning', ['laptop_z', 'smartphone_x', 'tablet_a'], 25),
    ('2024-01-01', 'new_customer', ['smartwatch_b', 'headphones_y', 'fitness_tracker'], 8),
    ('2024-01-02', 'returning', ['laptop_z', 'external_drive', 'laptop_z'], 30),
    ('2024-01-02', 'new_customer', ['tablet_a', 'keyboard_c', 'tablet_a'], 15),
    ('2024-01-02', 'premium', ['smartphone_x', 'smartwatch_b', 'headphones_y'], 22);

-- 按细分类型和参与度级别统计不重复产品数量
SELECT 
    session_date,
    -- 统计新客户在长会话中浏览的不重复产品数量
    uniqArrayIf(viewed_products, user_segment = 'new_customer' AND session_duration_minutes > 10) AS new_customer_engaged_products,
    -- 统计回头客浏览的不重复产品数量
    uniqArrayIf(viewed_products, user_segment = 'returning') AS returning_customer_products,
    -- 统计所有会话中浏览的不重复产品数量
    uniqArray(viewed_products) AS total_unique_products
FROM user_shopping_sessions
GROUP BY session_date
ORDER BY session_date
FORMAT Vertical;
```

```response title="Response" theme={null}
行 1:
──────
session_date:                2024-01-01
new_customer⋯ed_products:    2
returning_customer_products: 3
total_unique_products:       6

行 2:
──────
session_date:                2024-01-02
new_customer⋯ed_products:    2
returning_customer_products: 2
total_unique_products:       7
```

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

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