easy表转置

wfveoks0  于 2021-06-27  发布在  Hive
关注(0)|答案(3)|浏览(274)

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

Atr_1|Atr_2
 A   | 1
 A   | 2

但我想得到下一个结果

Atr_1|Atr_2|Atr_3
 A   | 1   |  2

为了达到这个结果,我应该如何转换我的表格?

vwoqyblh

vwoqyblh1#

如果只有两个值, min() 以及 max() 做你想做的:

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

l3zydbqr2#

用例语句 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;
px9o7tmv

px9o7tmv3#

我想你想要:

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;

相关问题