sql—如何获取配置单元中所有列的总和

enxuqcxy  于 2021-06-26  发布在  Hive
关注(0)|答案(1)|浏览(399)

可以获取配置单元表中所有列的总和。我是说任何一种求和的方法
表COLU 1 COLU 2 COLU 3
输出和(列)、和(列1)、和(列2)和(列3)

lp0sw83n

lp0sw83n1#

create table mytable (i int,j int,k int);
insert into mytable values (1,2,3),(4,5,6),(7,8,9);
select      pos+1       as col
           ,sum (val)   as sum_col 

from        mytable t 
            lateral view    posexplode(array(*)) pe 

group by    pos
;
+-----+---------+
| col | sum_col |
+-----+---------+
|   1 |      12 |
|   2 |      15 |
|   3 |      18 |
+-----+---------+

或者(上帝保佑我)

select      map_values
            (
                str_to_map
                (
                    concat_ws
                    (
                        ','
                       ,sort_array
                        (
                            collect_list
                            (
                                concat_ws
                                (
                                    ':'
                                   ,lpad(cast(pos as string),10,'0')
                                   ,cast(sum_val as string)
                                )
                            )
                        )
                    )
                )
            )       as sum_col_array 

from       (select      pos
                       ,sum (val)   as sum_val

            from        mytable t 
                        lateral view    posexplode(array(*)) pe 

            group by    pos
            ) t
;
+------------------+
|  sum_col_array   |
+------------------+
| ["12","15","18"] |
+------------------+

相关问题