使用sql进行hive表转置操作

时间:2018-05-09 08:55:06

标签: hive hiveql

我想使用hive QL转置表 这是下面的源表

___________________________________________
subject|roll_1|roll_2|roll_3|roll_4|roll_5|
___________________________________________
MATHS  |80    | 90   |   78 |   95 |    68|
___________________________________________
ENGLISH|78    | 78   | 67   |75    |54    |

我希望以下表所示的格式回答

subject|MATHS|ENGLISH|
______________________
roll_1 |80   |78     |
______________________
roll_2 |90   |78     |
______________________
roll_3 |78   | 67    |
______________________
roll_4 |95   |75     |
______________________
roll_5 |68   |54     |

请帮我恢复这个

2 个答案:

答案 0 :(得分:1)

这是我最接近通用的,因为添加了新列,您只需要在 < CONCAT() 中进行更改EM>地图()

select pos1+1 AS rollnum,mat,eng from(
  select collect_list(a.group_map['MATHS']) as MATHS,
         collect_list(a.group_map['ENGLISH']) as ENGLISH,
         from ( select map(SUBJECT,CONCAT(ROLL1,',',ROLL2,',',ROLL3,',',ROLL4,',',
                                                   ROLL5,',',ROLL6)) as group_map
                                                    from db_name.tbl_name) a) b
         lateral view posexplode(split(b.MATHS[0],',')) MATHS AS pos1,mat
         lateral view posexplode(split(b.ENGLISH[0],',')) ENGLISH AS pos2,eng

         WHERE pos1=pos2 

虽然这可能会影响效率。

答案 1 :(得分:0)

以下是获取所需输出的SQL。

select 'roll_1' as subject,sum(case when subject='MATHS' then roll_1 else 0 end) maths,sum(case when subject='ENGLISH' then roll_1 else 0 end) english from your_table_2
union all
select 'roll_2' as subject,sum(case when subject='MATHS' then roll_2 else 0 end) maths,sum(case when subject='ENGLISH' then roll_2 else 0 end) english from your_table_2
union all
select 'roll_3' as subject,sum(case when subject='MATHS' then roll_3 else 0 end) maths,sum(case when subject='ENGLISH' then roll_3 else 0 end) english from your_table_2
union all
select 'roll_4' as subject,sum(case when subject='MATHS' then roll_4 else 0 end) maths,sum(case when subject='ENGLISH' then roll_4 else 0 end) english from your_table_2
union all
select 'roll_5' as subject,sum(case when subject='MATHS' then roll_5 else 0 end) maths,sum(case when subject='ENGLISH' then roll_5 else 0 end) english from your_table_2