0

我有以下地址数据:

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

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

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

谢谢。

4

2 回答 2

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

在此处查看小提琴。

于 2013-10-18T07:37:17.053 回答
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 演示

于 2013-10-18T07:38:54.977 回答