Clickhouse 的 SQL 中的 Unpivot 操作

问题描述 投票:0回答:1

我正在使用 SQL 创建 Clickhouse 数据库。

我有一个包含以下数据的表格:

┌─report_date──┬─platform─┬─viewers─┬─effectivePlaytime─┬─revenue─┐
│ Date         │ String   │ UInt32  | Float32           │ Float32 |
└──────────────┴──────────┴─────────┴───────────────────┴─────────┘

我想对此表执行一项操作,该操作可以描述为逆透视操作。这是每个指标、日期和平台提取一行,而不是常规

select * from data_table
返回的通常每个平台和数据一行。

这就是我需要在回复中得到的内容。

┌─report_date──┬─platform─┬─metric ─┬─Value───┐
│ Date         │ String   │ String  | Float32 │
└──────────────┴──────────┴─────────┴─────────┘

我当前的尝试是执行多个

UNION ALL
,它会产生我想要的结果,但是,我希望有一个更好的(更紧凑并且可能更快)的解决方案。

SELECT report_date, platform, 'viewers' AS metric, viewers AS value
FROM platform_table
UNION ALL
SELECT report_date, platform, 'effectivePlaytime' AS metric, effectivePlaytime AS value
FROM platform_table
UNION ALL
SELECT report_date, platform, 'revenue' AS metric, revenue AS value
FROM platform_table
sql clickhouse
1个回答
0
投票

你想要

ARRAY JOIN
。试试这个:

SELECT
    report_date,
    platform,
    metric,
    value
FROM platform_table
ARRAY JOIN
    splitByString(',', 'viewers,effectivePlaytime,revenue') AS metric,
    [viewers, effectivePlaytime, revenue] AS value;
© www.soinside.com 2019 - 2024. All rights reserved.