sql—将配置单元中的行转换为列

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

我在 hive 里有一张table,结构如下:

+------+------+--------+-------+
| col1 | col2 |  col3  | Value |
+------+------+--------+-------+
|    1 | A1   | M1     |    23 |
|    1 | A1   | M1_LW  |    25 |
|    1 | A1   | M1_L2W |    22 |
|    1 | A1   | M2     |    17 |
|    1 | A1   | M2_LW  |    21 |
|    1 | A1   | M2_L2W |    13 |
|    1 | A1   | M3     |    16 |
|    1 | A1   | M3_LW  |    30 |
|    1 | A1   | M3_L2W |    11 |
|    2 | A2   | M1     |    22 |
|    2 | A2   | M1_LW  |    22 |
|    2 | A2   | M1_L2W |    10 |
|    2 | A2   | M2     |    14 |
|    2 | A2   | M2_LW  |    25 |
|    2 | A2   | M2_L2W |    23 |
|    2 | A2   | M3     |    10 |
|    2 | A2   | M3_LW  |    20 |
|    2 | A2   | M3_L2W |    25 |
+------+------+--------+-------+

从查询的Angular 来看,此结构足以满足需要,但对于特定的报告需要,需要将表转换为如下所示:

+------+------+-------+----+----+----+
| col1 | col2 | col3  | M1 | M2 | M3 |
+------+------+-------+----+----+----+
|    1 | A1   | Today | 23 | 17 | 16 |
|    1 | A1   | LW    | 25 | 21 | 30 |
|    1 | A1   | L2W   | 22 | 13 | 11 |
|    2 | A2   | Today | 22 | 14 | 10 |
|    2 | A2   | LW    | 22 | 25 | 20 |
|    2 | A2   | L2W   | 10 | 23 | 25 |
+------+------+-------+----+----+----+

你能帮助下面使用Hive中的内置功能吗。我试过在结果上使用case for pivot和union,但这样做会造成性能开销。尝试使用to\u map udaf,但所使用的配置单元版本似乎不支持它。任何意见都将不胜感激。

j2cgzkjk

j2cgzkjk1#

你可以用 case 和条件聚合:

select col1, col2,
       (case when col3 like '%_LW' then 'LW'
             when col3 like '%_L2W' then 'L2W'
             else 'Today'
        end) as col3,
       max(case when col3 like 'M1%' then value end) as m1,
       max(case when col3 like 'M2%' then value end) as m2,
       max(case when col3 like 'M3%' then value end) as m3
from t
group by col1, col2,
         (case when col3 like '%_LW' then 'LW'
               when col3 like '%_L2W' then 'L2W'
               else 'Today'
          end)

相关问题