uniqArrayIf — 조건을 만족하는 행의 배열 고유 값 개수 세기
uniqArrayIf — 조건을 만족하는 행의 배열 고유 값 개수 세기
uniqArrayIf는 uniq 함수에 Array와 If 결합자를 적용해서 조건이 참인 행의 배열 안 고유 값 개수를 세는 방법을 보여드릴게요.
출처: 문서
본문
uniq 함수에 Array와 If 결합자를 적용하면 조건이 참인 행의 배열 안 고유 값 개수를 세는데, 이때 uniqArrayIf 집계 결합자 함수를 사용해요.
-If와 -Array는 함께 쓸 수 있어요. 하지만 Array가 먼저 와야 하고 그 다음 If가 와야 해요.
이는 arrayJoin을 쓰지 않고도 특정 조건에 따라 배열 안 고유 요소를 세고 싶을 때 유용해요.
세그먼트 유형과 참여 수준별 조회한 고유 제품 수 세기
이 예제에서는 사용자 쇼핑 세션 데이터가 있는 테이블을 사용해서, 특정 사용자 세그먼트에 속한 사용자가 세션에서 보낸 시간이라는 참여 지표와 함께 조회한 고유 제품 수를 세어볼게요.
Query
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);
-- Count unique products viewed by segment type and engagement level
SELECT
session_date,
-- Count unique products viewed in long sessions by new customers
uniqArrayIf(viewed_products, user_segment = 'new_customer' AND session_duration_minutes > 10) AS new_customer_engaged_products,
-- Count unique products viewed by returning customers
uniqArrayIf(viewed_products, user_segment = 'returning') AS returning_customer_products,
-- Count unique products viewed across all sessions
uniqArray(viewed_products) AS total_unique_products
FROM user_shopping_sessions
GROUP BY session_date
ORDER BY session_date
FORMAT Vertical;
Response
Row 1:
──────
session_date: 2024-01-01
new_customer⋯ed_products: 2
returning_customer_products: 3
total_unique_products: 6
Row 2:
──────
session_date: 2024-01-02
new_customer⋯ed_products: 2
returning_customer_products: 2
total_unique_products: 7