これは基本的に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 |