2016-12-29 1 views
0

여러 행 데이터를 단일 열로 가져 가려고 애 쓰고 있습니다.HiveQL - 단일 행에 여러 행 데이터 집계

site  country users country _rank 
cnn.com  840  10000 1 
cnn.com  31   4000  3 
cnn.com  556  6000  2 
rt.com  840  200  3 
rt.com  33   6000  2 
rt.com  400  10000 1 

를 내가 얻으려고 노력하고 결과는 상위 2 개국에 대한 사용자의 #를 받아 단일 행에 넣습니다 : 여기에 예를 제공하기 위해 테이블 ​​나는이되어

site  country_1 country_1_share  country_2  country_2_share 
cnn.com 840   10000    556   6000 
rt.com  400   10000    33   6000 

또한

select site, country_1, country_1_share,country_2,country_2_share 
from (
    select site 
    ,max(CASE WHEN country_rank = 1 THEN country END) AS country_1 
    ,max(CASE WHEN country_rank = 1 THEN users END) as country_1_share 
    ,max(CASE WHEN country_rank = 2 THEN country END) AS country_2 
    ,max(CASE WHEN country_rank = 2 THEN users END) as country_2_share 
    from t1 
    group by site 
) 

과 :

select a.site, a.country_1, b.country_1_share,c.country_2,d.country_2_share 
from (
    select site, country as country_1 
    from t1 
    where max(CASE WHEN country_rank = 1 THEN country END)) a 
JOIN (
    select site, users as country_1_share 
    from t1 
    where max(CASE WHEN country_rank = 1 THEN users END)) b on (a.site=b.site) 
JOIN (
    select site, country as country_2 
    from t1 
    where max(CASE WHEN country_rank = 2 THEN country END)) c on (a.site = c.site) 
JOIN (
    select site, users as country_2_share 
    from t1 
    where max(CASE WHEN country_rank = 2 THEN users END)) d on (a.site = c.site) 
,691,363 나는이 몇 가지 방법을 수행하려고했습니다210

어떤 통찰력이라도 대단히 감사 할 것입니다!

답변

1

이 하이브 1.2.1에서 잘 작동합니다

drop table if exists t1; 

create table t1 
as 
select 'cnn.com' site, 840 country , 10000 users, 1 country_rank union all 
select 'cnn.com' site, 31 country , 4000 users, 3 country_rank union all 
select 'cnn.com' site, 556 country , 6000 users, 2 country_rank union all 
select 'rt.com' site, 840 country , 200 users, 3 country_rank union all 
select 'rt.com' site, 33 country , 6000 users, 2 country_rank union all 
select 'rt.com' site, 400 country , 10000 users, 1 country_rank; 

select site, country_1, country_1_share,country_2,country_2_share 
from (
    select site 
    ,max(CASE WHEN country_rank = 1 THEN country END) AS country_1 
    ,max(CASE WHEN country_rank = 1 THEN users END) as country_1_share 
    ,max(CASE WHEN country_rank = 2 THEN country END) AS country_2 
    ,max(CASE WHEN country_rank = 2 THEN users END) as country_2_share 
    from t1 
    group by site 
)s; 



OK 
site country_1  country_1_share country_2  country_2_share 
cnn.com 840  10000 556  6000 
rt.com 400  10000 33  6000 
+0

감사합니다! 하위 쿼리를 정의하는 것만 큼 필요한 것처럼 보입니다. (예제에서 ";"당신은 올바른 방향으로 나를 가리키고있었습니다. –

관련 문제