Files
homework/mdrozdov/clickhouse/merge_tree_family.sql
T
2026-01-31 03:29:26 +07:00

64 lines
1.4 KiB
SQL

--page_views table
create table page_views (
user_id UInt64,
url String,
view_time DateTime
)
Engine = MergeTree
Order by (user_id, view_time)
Partition by toYYYYMM(view_time)
-- users table
create table users(
id UInt64,
name String,
updated_at DateTime
)
ENGINE = ReplacingMergeTree(updated_at)
Order by id;
-- region_sales table
create table mdrozdov.region_sales(
region String,
date Date,
sales UInt64
)
ENGINE = SummingMergeTree
Partition by toYYYYMM(date)
Order by (region, date)
insert into mdrozdov.region_sales (region, date, sales)
values ('Russia', '2025-01-14', 30), ('Russia', '2025-01-16', 22), ('USA', '2025-01-14', 1400)
OPTIMIZE TABLE mdrozdov.region_sales FINAL
-- user_metrics table
create table mdrozdov.user_metrics (
region String,
avg_age_state AggregateFunction(avg, UInt8),
active_users_state AggregateFunction(uniq, UInt64)
)
Engine = AggregatingMergeTree
Order by region
INSERT INTO mdrozdov.user_metrics
SELECT
'Moscow' AS region,
avgState(toUInt8(25)) AS avg_age_state,
uniqState(toUInt64(100)) AS active_users_state
UNION ALL
SELECT
'Moscow',
avgState(toUInt8(30)),
uniqState(toUInt64(50))
UNION ALL
SELECT
'SPB',
avgState(toUInt8(20)),
uniqState(toUInt64(10));
SELECT
region,
avgMerge(avg_age_state) AS avg_age,
uniqMerge(active_users_state) AS active_users
FROM mdrozdov.user_metrics
GROUP BY region