SQL 将多列转为一列,一行转为多行 (odps sql)

准备数据

create table if not exists tmp_table_friends
(
    name string comment '名字',
    appearance double comment '外貌',
    character double comment '性格',
    ability double comment '能力',
    humor double comment '幽默',
    job double comment '工作',
    figure double comment '外形',
    family double comment '家庭'
);

insert into tmp_table_friends
(name,appearance,character,ability,humor,job,figure,family) 
values
('Elizabeth',90,89,70,78,69,60,70),
('Bella',99,80,60,65,60,80,70),
('Melody',60,90,90,80,88,65,89),
('CC',92,80,66,69,70,89,80),
('Lili',90,80,80,60,70,80,60);

select * from tmp_table_friends ;

SQL 将多列转为一列,一行转为多行 (odps sql)_第1张图片

将多列转为一列,一行转为多行,并输出top3的特征;

select distinct 
    d.name,
    d.feature_type,
    d.feature_num, 
    d.feature_num_order
from(
    select 
        c.name,
        c.feature_type,
        c.feature_num,
        ROW_NUMBER()over(partition by c.name order by c.feature_num desc) as feature_num_order
    from(
        select distinct 
            b.name,
            split_part(b.feature,':',1) as feature_type,
            cast(split_part(b.feature,':',2) as double) as feature_num
        from(
            select 
                trans_cols(1,a.name,a.appearance,a.character,a.ability,a.humor,a.job,a.figure,a.family) as (idx,name,feature)
            from(
                select distinct 
                    name,
                    concat('appearance:',appearance) as appearance,
                    concat('character:',character) as character,
                    concat('ability:',ability) as ability,
                    concat('humor:',humor) as humor,
                    concat('job:',job) as job,
                    concat('figure:',figure) as figure,
                    concat('family:',family) as family
                from tmp_table_friends
                where name is not null
            ) a
        ) b
    ) c
) d
where d.feature_num_order<=3
;

SQL 将多列转为一列,一行转为多行 (odps sql)_第2张图片

 

你可能感兴趣的:(data,sql,mysql,大数据)