2017-03-09 167 views
1

我有蜂巢的表有以下的列加盟蜂巢

userid     string 
attribute_name   string 
attribute_value   string 

attribute_name可以像年齡的數值,性別等的屬性值是該名稱的值,寫成M性別。我想要的是一個表,它對每個用戶標識都有一個特定的attribute_name聚合的所有值。例如,如果這是一個示例表

userid attribute_name attribute_value 
1000  gender   M 
1000  city    Perth 
1000  city    Singapore 
1001  gender   F 
1001  city    Tokyo 
1001  gender   M 
1002  city    Bombay 

我想獲得

1000  {M}  {Perth, Singapore} 
1001  {F,M} {Tokyo} 

的括號只是爲了清楚。

我可以得到兩個單獨的表,可能然後做一個連接,但我試圖做一個單一的步驟

select userid, count (DISTINCT table.attribute_value) as numgender, collect_set(table.attribute_value) as genders               

從表,其中屬性名稱==「性別」 GROUP BY table.userid

類似的城市可以在單個查詢中完成嗎?

回答

2
select  userid 
      ,concat_ws(',',collect_list (case when attribute_name = 'gender' then attribute_value end)) as genders 
      ,concat_ws(',',collect_list (case when attribute_name = 'city' then attribute_value end)) as cities 

from  mytable 

group by userid 
; 

+--------+---------+-----------------+ 
| userid | genders |  cities  | 
+--------+---------+-----------------+ 
| 1000 | M  | Perth,Singapore | 
| 1001 | F,M  | Tokyo   | 
| 1002 |   | Bombay   | 
+--------+---------+-----------------+ 

爲了過濾掉用戶標識沒有性別 -

having count (case when attribute_name = 'gender' then 1 end) > 0 
+1

檢查更新的答案 –

+0

如果我不想行什麼,其中性別是空的,如1002在上面的例子中。如何過濾掉?謝謝。 – Farhat

+0

檢查已更新的答案以回答您的問題 –