2014-03-07 152 views
0

這是我的數據庫表。我想要檢索水平鍵值爲垂直。從數據庫檢索數據爲verital

city_id cat_id value 
    100  1  1000 
    100  2  2000 
    101  1  350 
    101  2  500 
    102  1  1000 
    102  2  2000 
    103  1   10 
    104  2   5 

輸出:

city_id catagory1 catagory2 
100  1000   2000 
101   350   500 
102  1000   2000 
103   10    0 
104   0    5 

回答

3

你需要一個支點結果:

select 
    city_id, 
    max(case cat_id when 1 then value else 0 end) as category_1, 
    max(case cat_id when 2 then value else 0 end) as category_2 
from 
    my_table 
group by 
    city_id 
1

我應該告訴你使用GROUP_CONCAT

您的所有類別只有一列。你只需要將它們分開。

SELECT city_id, GROUP_CONCAT(value SEPARATOR ', ') as categories 
FROM your_table 
GROUP BY city_id 

這是SqlFiddle

+0

不正是...... http://sqlfiddle.com/#!2/ce8a1/1 – djot

+0

'GROUP BY city_id'做它...的http:/ /sqlfiddle.com/#!2/ce8a1/3 ...現在誰得分?對... – djot

+0

對,現在我已經完成了自己! ;)你得到分數! :) – kmas