其他分享
首页 > 其他分享> > Hive练习题之列转行

Hive练习题之列转行

作者:互联网

源数据

+-----------+-------+-------+-------+
| grade_id  |  yw   |  sx   |   zz  |
+-----------+-------+-------+-------+
| 1         | 98.0  | 0.0   | 0.0   |
| 2         | 0.0   | 80.0  | 78.0  |
| 5         | 88.0  | 66.0  | 99.0  |
+-----------+-------+-------+-------+
1,98.0,0.0,0.0
2,0.0,80.0,78.0
5,88.0,66.0,99.0

想得到的结果:

 +--------------+------------------+---------------+
|    grade_id  |  subject_name    |  max_score    |
+--------------+------------------+---------------+
| 1            | 语文               | 98.0        |
| 2            | 数学               | 80.0        |
| 2            | 政治               | 78.0        |
| 5            | 语文               | 88.0        |
| 5            | 数学               | 66.0        |
| 5            | 政治               | 99.0        |
+--------------+------------------+---------------+

建表

create table if not exists test.ms2 (grade_id int, yw double, ss double, zz double)
row format delimited fields terminated by ",";

导入数据

load data local inpath "/doit16/ms2.txt" into table ms2;

解法1:

SELECT grade_id
    ,split(cs, ':') [0] AS subject_name
    ,split(cs, ':') [1] AS score
FROM (
    SELECT grade_id
        ,concat_ws(',', cast(yw AS string), cast(ss AS string), cast(zz AS string)) AS sub_score
    FROM (
        SELECT grade_id
            ,concat_ws(':', 'yw', cast(yw AS string)) AS yw
            ,concat_ws(':', 'ss', cast(ss AS string)) AS ss
            ,concat_ws(':', 'zz', cast(zz AS string)) AS zz
        FROM ms2
        ) t1
    ) t2 LATERAL VIEW explode(split(sub_score, ',')) susc AS cs;

在这里插入图片描述

标签:练习题,string,grade,0.0,转行,Hive,zz,id,yw
来源: https://blog.csdn.net/weixin_43648241/article/details/122806049