可以将 Array 和 If 组合器应用于 uniq
函数,使用 uniqArrayIf 聚合组合器函数统计条件为真的
行中数组内唯一值的数量。
-If 和 -Array 可以组合使用。不过,Array 必须在前,If 在后。
当你想基于特定条件统计数组中的唯一元素,又不想使用 arrayJoin 时,
这会非常有用。
在本示例中,我们将使用一张包含用户购物会话数据的表,统计特定用户细分中、
以会话停留时间作为参与度指标的用户所浏览过的唯一产品数量。
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;
行 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