我有一个表,其中包含每个产品的数据,它们具有某些属性,例如(目前仅限于 A、B、C)。我有每个属性对应的值。
Product Attribute Value
p1 A 1
p1 B 2
p1 C 3
p2 A 1
p3 B 3
p3 C 2
我希望我的输出是:
Product A B C
1 1 2 3
2 1 NULL NULL
3 NULL 3 2
到目前为止我所尝试的是,它最终确实给了我想要的东西,但是这个查询完全是一个大问题,我来自 R 背景,我想知道它们是否是一个简单的解决方案或类似的解决方案来自 R 中的 reshape
的 cast
。
谢谢!
select
product,
max(`A`) as A,
max(`B`) as B,
max(`C`) as C
from
(select
product,
case attribute when 'A' then `value` else null end as A,
case attribute when 'B' then `value` else null end as B,
case attribute when 'C' then `value` else null end as C
from test) t
group by product
最佳答案
我不知道 Hive 中有 pivot
函数,但这是可能的。您需要将属性和值收集到 map ,这可以使用此 UDAF 来完成
示例:
ADD JAR /root/path/to/jar/brickhouse-0.7.0.jar;
CREATE TEMPORARY FUNCTION collect AS 'brickhouse.udf.collect.CollectUDAF';
SELECT product
, attr_map['A'] AS A
, attr_map['B'] AS B
, attr_map['C'] AS C
FROM (
SELECT product
, collect(attribute, value) AS attr_map
FROM test
GROUP BY product
) x
这里需要注意的是,如果您有很多属性,这可能会是相当多的重复代码。
关于mysql - 将多行转变成多列的一行(就像 R 中的 reshape 类型转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26920309/