clickhouse行转列
时间: 2023-09-13 18:13:14 浏览: 279
在ClickHouse中,可以使用arrayJoin()函数将分割结果转换为列。具体的语法如下:
SELECT 字段1, 字段2, 字段3, 字段4, arrayJoin(splitByString(' ',Name)) AS chaifen from 表名; [1]
如果要将表中的行转换为列,可以使用普通写法(使用CASE WHEN语句)或基于multiIf / if的写法。例如,将学生的成绩表中每行表示一科的成绩转换为每个学生所有科的成绩在一行展示,可以使用以下语句:
普通写法(使用CASE WHEN语句):
SELECT student_name,
SUM(CASE WHEN subject='语文' THEN score ELSE 0 END) as Chinese,
SUM(CASE WHEN subject='数学' THEN score ELSE 0 END) as Math,
SUM(CASE WHEN subject='英语' THEN score ELSE 0 END) as English,
SUM(CASE WHEN subject='特长加分' THEN score ELSE 0 END) as Special
FROM t_gaokao_score
GROUP BY student_name; [2]
基于multiIf / if的写法:
SELECT student_name,
SUM(multiIf(subject='语文', score, 0)) as Chinese,
SUM(multiIf(subject='数学', score, 0)) as Math,
SUM(multiIf(subject='英语', score, 0)) as English,
SUM(multiIf(subject='特长加分', score, 0)) as Special
FROM t_gaokao_score
GROUP BY student_name; [2]
如果要将表中的列转换为行,可以使用普通写法(使用UNION ALL语句)或基于arrayJoin的写法。例如,将表中的列id、a、b、c转换为行,可以使用以下语句:
普通写法(使用UNION ALL语句):
SELECT id, a AS newCol FROM test
UNION ALL
SELECT id, b AS newCol FROM test
UNION ALL
SELECT id, c AS newCol FROM test; [3]
基于arrayJoin的写法:
SELECT id, arrayJoin(arrayConcat(groupArray(a), groupArray(b), groupArray(c))) AS newCol
FROM test
GROUP BY id
ORDER BY newCol; [3]
希望以上信息对您有所帮助!
阅读全文