2

次のようなテーブルがあります。

userid    cityid
1         4
1         5
2         4
2         1
3         1
3         5

SQLまたはハイブで次のようなテーブルに変換する方法はありますか?

userid    city1    city4   city5
1         false    true    true
2         true     true    fase
3         true     false   true

この種の操作を説明する言葉があるかどうかはわかりません...どんな助けもいただければ幸いです!

4

1 に答える 1

7

これは基本的にPIVOT. 使用している RDBMS を指定しませんでしたが、集計関数とCASEステートメントを使用して任意の DB で結果を取得できます。

select userid,
  max(case when cityid = 1 then 'true' else 'false' end) city1,
  max(case when cityid = 2 then 'true' else 'false' end) city2,
  max(case when cityid = 3 then 'true' else 'false' end) city3,
  max(case when cityid = 4 then 'true' else 'false' end) city4,
  max(case when cityid = 5 then 'true' else 'false' end) city5
from yourtable
group by userid

デモで SQL Fiddle を参照してください

結果:

| USERID | CITY1 | CITY2 | CITY3 | CITY4 | CITY5 |
--------------------------------------------------
|      1 | false | false | false |  true |  true |
|      2 |  true | false | false |  true | false |
|      3 |  true | false | false | false |  true |
于 2012-11-09T14:46:47.410 に答える