sql基于一列的不同值创建多个列

ijxebb2r  于 2021-06-26  发布在  Hive
关注(0)|答案(2)|浏览(359)

我有一张这样的table

-------------------------------
| col1 | col2 | count | value |
-------------------------------
| id1  | val1 | 1     |   2   | 
| id1  | val2 | 3     |   4   |
| id2  | val1 | 5     |   6   | 
| id2  | val2 | 7     |   8   |

....

我希望最终结果是这样的

---------------------------------------------------------------
| col1 | val1_count| val1_value| val2_count | val2_value | ... 
---------------------------------------------------------------
| id1  | 1         |  2        |   3        |  4         | 
| id2  | 5         |  6        |   7        |  8         |
....

它基本上是excel中的pivot表或python/r中的melt/cast,但是有一个优雅的sql解决方案来实现它吗?幸运的是,col2-val1和val2只有两个不同的值,但是如果有一个解决方案可以扩展到除两个以外的多个值,这将是一个额外的点。
更新,我正在使用Hive和 Impala (我都可以使用)

bxjv4tth

bxjv4tth1#

一种方法是

select col1, 
       max(case when col2 = 'val1' then count else null end) as val1_count,
       max(case when col2 = 'val1' then value else null end) as val1_value,
       max(case when col2 = 'val2' then count else null end) as val2_count,
       max(case when col2 = 'val2' then value else null end) as val2_value
from your_table
group by col1
jc3wubiy

jc3wubiy2#

一个简单的方法是 join :

select t1.col1, t1.count as val1_count, t1.value as val1_value,
       t2.count as val2_count, t2.value as val2_value
from t t1 left join
     t t2
     on t1.col1 = t2.col1 and t2.col2 = 'val2'
where t1.col2 = 'val1';

这是标准的sql,应该可以在任何数据库中使用。

相关问题