MySQL Flip数据,如Cross Tab

时间:2013-10-18 07:20:55

标签: mysql crosstab

我有以下地址数据:

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

是否存在基于ID的SQL hack或简单方法来翻转此数据,以便将以下结果分散到多个地址字段中:

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

感谢。

2 个答案:

答案 0 :(得分:0)

如果你知道每个地址的行数最多为3,你可以使用这样的hack:

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

答案 1 :(得分: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 演示