You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Clickhouse中基于type和subtype实现单列转多列的方法

ClickHouse行转列消除NULL值方案

原始数据

datevaluetypesubtype
2021-01-011Ax
2021-01-012Ay
2021-01-013Bx
2021-01-014By
2021-01-025Ax
2021-01-026Ay
2021-01-027Bx
2021-01-028By

目标格式

dateAxAyBxBy
2021-01-011234
2021-01-025678

问题重现

使用以下查询时,返回结果包含大量NULL值,每条记录仅单个字段有值:

SELECT
    date,
    case when type = 'A' and subtype = 'x' then value end Ax,
    case when type = 'A' and subtype = 'y' then value end Ay,
    case when type = 'B' and subtype = 'x' then value end Bx,
    case when type = 'B' and subtype = 'y' then value end By
FROM my_table

解决方案

通过聚合函数+分组将同一日期的行合并,过滤NULL值。由于每个date + type + subtype组合仅存在一条记录,使用max()或sum()聚合均可:

SELECT
    date,
    max(case when type = 'A' and subtype = 'x' then value end) AS Ax,
    max(case when type = 'A' and subtype = 'y' then value end) AS Ay,
    max(case when type = 'B' and subtype = 'x' then value end) AS Bx,
    max(case when type = 'B' and subtype = 'y' then value end) AS By
FROM my_table
GROUP BY date

原理说明

  • 聚合函数max()会自动忽略NULL值,仅保留分组内对应字段的非NULL值(此处每个分组对应字段仅一个非NULL值)。
  • GROUP BY date将同一日期的所有行合并为一行,正好匹配目标格式的结构。

内容的提问来源于stack exchange,提问作者greg0r

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 05:05:03