繁体   English   中英

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

[英]SQL create multiple columns based on distinct value of one column

我有一张桌子看起来像这样

-------------------------------
| 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中的数据透视表,还是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,可以在任何数据库中使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM