SQL 根据一列的不同值创建多列

SQL create multiple columns based on distinct value of one column

我有一个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 中的支点 table 或 Python/R 中的 melt/cast 但是否有一个优雅的 SQL 解决方案来实现它?幸运的是,col2 只有两个不同的值 - val1、val2,但如果有一个解决方案可以扩展到除两个以外的许多值,那将是加分项。

更新,我正在使用 Hive 和 Impala(我都可以使用)

一种方法是

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

一个简单的方法使用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,应该适用于任何数据库。