2012-11-09 32 views
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 

我不知道有沒有一個詞來形容這種操作... 任何幫助將不勝感激!

+2

你可能可以用PIVOT來處理(假設ID不固定爲1,4,5)。對於SQL Server請參閱:http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx。有些人也可能將你正在尋找的結果稱爲交叉表。 – rsbarro

+0

你使用的是什麼rdbms? – Taryn

回答

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 with Demo

結果:

| USERID | CITY1 | CITY2 | CITY3 | CITY4 | CITY5 | 
-------------------------------------------------- 
|  1 | false | false | false | true | true | 
|  2 | true | false | false | true | false | 
|  3 | true | false | false | false | true |