简易表在蜂巢中转置

时间:2019-02-05 12:24:50

标签: sql hive

我需要调换桌子。 现在我有了这种类型的表:

Atr_1|Atr_2
 A   | 1
 A   | 2

但是我想得到下一个结果

Atr_1|Atr_2|Atr_3
 A   | 1   |  2

我应该如何调换桌子以获得这个结果?

3 个答案:

答案 0 :(得分:1)

如果只有两个值,min()max()会执行您想要的操作:

select atr_1, min(atr_2) as atr_2, max(atr_3) as atr_3
from t
group by atr_1;

答案 1 :(得分:1)

我认为您想要汇总:

SELECT atr_1, 
       MAX(CASE WHEN SEQ = 1 THEN atr_2 END) as atr_2,
       MAX(CASE WHEN SEQ = 2 THEN atr_2 END) as atr_3
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY atr_1 ORDER BY atr_2) AS SEQ
      FROM table t
     ) t
GROUP BY atr_1;

答案 2 :(得分:1)

具有min()max()聚合的用例语句:

select Atr_1,
       max(case when Atr_2=1 then 1 end ) Attr_2,
       max(case when Atr_2=2 then 2 end ) Attr_3
  from table t
 group by Atr_1;