2013-10-18 87 views
0

,我有以下地址數據:MySQL的翻轉數據,如交叉表

ID  Address 
--------------- 
1  123 Riverside Drive 
1  Pleasantvile 
1  Some Country 
2  96 Another Street 
2  Europe 

是否有一個SQL黑客或一個簡單的方法來翻轉這個數據的基礎上,ID,讓我有以下結果攤開成幾個地址字段:

ID  Address1    Address2  Address3 
---------------------------------------------------------- 
1  123 Riverside Drive Pleasantvile Some Country 
2  96 Another Street Europe 

謝謝。

+0

最簡單的方法是創建另一個表查詢來填充。 – learningloop

+0

您必須在應用程序的數據庫層中執行此操作嗎?你不能在表示層中做它嗎? – eggyal

+0

這是查詢填充另一個表,我不知道。是的,它必須在數據庫中完成 - 沒有應用程序。想不到一種翻轉數據的方式。 – user1236443

回答

0

如果你不事先知道每個ID地址數量

SET @sql = NULL; 

SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(CASE WHEN rnum = ', rnum, 
          ' THEN address END) `address', rnum, '`')) 
    INTO @sql 
    FROM 
(
    SELECT id, address, @n := IF(@g = id, @n + 1, 1) rnum, @g := id 
    FROM table1 CROSS JOIN (SELECT @n := 0, @g := NULL) i 
    ORDER BY id, address 
) q; 

SET @sql = CONCAT('SELECT id,', @sql, 
        ' FROM 
        (
        SELECT id, address, @n := IF(@g = id, @n + 1, 1) rnum, @g := id 
         FROM table1 CROSS JOIN (SELECT @n := 0, @g := NULL) i 
        ORDER BY id, address 
       ) q 
        GROUP BY id'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

這裏是SQLFiddle演示

+0

工程就像一個魅力 - 謝謝。 – user1236443

0

如果你知道行對每個地址的數量爲最多三個,你可以使用一個黑客就像這樣:

SELECT 
    ID, 
    MAX(CASE WHEN Rownum=1 THEN Address END) As Address1, 
    MAX(CASE WHEN Rownum=2 THEN Address END) As Address2, 
    MAX(CASE WHEN Rownum=3 THEN Address END) As Address3 
FROM (
    SELECT 
    ID, 
    @row:=CASE WHEN @lastid=id THEN @row+1 ELSE 1 END AS Rownum, 
    Address, 
    @lastid:=id 
    FROM 
    addresses 
    ORDER BY 
    id, Address 
) s 
GROUP BY 
    ID 

請參閱小提琴here