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

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

我有一张这样的table

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

我希望最终结果是这样的

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

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

bxjv4tth

bxjv4tth1#

一种方法是

  1. select col1,
  2. max(case when col2 = 'val1' then count else null end) as val1_count,
  3. max(case when col2 = 'val1' then value else null end) as val1_value,
  4. max(case when col2 = 'val2' then count else null end) as val2_count,
  5. max(case when col2 = 'val2' then value else null end) as val2_value
  6. from your_table
  7. group by col1
jc3wubiy

jc3wubiy2#

一个简单的方法是 join :

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

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

相关问题