用于将行转换为列的动态SQL代码

时间:2015-09-09 05:43:41

标签: mysql pivot-table

我在MySQL中有一个像这样的表:

+-------+----------+
|  am   | ipiresia |
+-------+----------+
| 50470 |       29 |
| 50470 |       43 |
| 50433 |       29 |
|  6417 |       51 |
|  6417 |       52 |
|  6417 |       53 |
|  4960 |       25 |
|  4960 |       26 |
|  5567 |       89 |
|  6716 |       88 |
+-------+----------+

我想像这样改造它:

+-------+-----------+-----------+-----------+
|  am   | ipiresia1 | ipiresia2 | ipiresia3 |
+-------+-----------+-----------+-----------+
| 50470 |        29 |        43 |           |
| 50433 |        29 |           |           |
|  6417 |        51 |        52 |        53 |
|  4960 |        25 |        26 |           |
|  5567 |        89 |           |           |
|  6716 |        88 |           |           |
+-------+-----------+-----------+-----------+

当然这只是表格的一部分。最多出现的是'ipiresia' per' per'可以达到5,所以我认为动态数据透视表可以完成工作,但我不知道该怎么做。

2 个答案:

答案 0 :(得分:1)

首先 - 再添加一个包含精确ipiresia个数字的列 -

+-------+----------+-----+
|  am   | ipiresia | num |
+-------+----------+-----+
| 50470 |       29 |   1 |
| 50470 |       43 |   2 |
| 50433 |       29 |   1 |
|  6417 |       51 |   1 |
|  6417 |       52 |   2 |
|  6417 |       53 |   3 |
|  4960 |       25 |   1 |
|  4960 |       26 |   2 |
|  5567 |       89 |   1 |
|  6716 |       88 |   1 |
+-------+----------+-----+

然后使用动态轴 -

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(num = ''',
      num,
      ''', ipiresia, NULL)) AS ',
      CONCAT('ipiresia', num)
    )
  ) INTO @sql
FROM ipiresia;
SET @sql = CONCAT('SELECT am, ', @sql, ' FROM ipiresia GROUP BY am');

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

结果 -

+-------+-----------+-----------+-----------+
| am    | ipiresia1 | ipiresia2 | ipiresia3 |
+-------+-----------+-----------+-----------+
|  4960 |        25 |        26 |      NULL |
|  5567 |        89 |      NULL |      NULL |
|  6417 |        51 |        52 |        53 |
|  6716 |        88 |      NULL |      NULL |
| 50433 |        29 |      NULL |      NULL |
| 50470 |        29 |        43 |      NULL |
+-------+-----------+-----------+-----------+

Automate pivot table queries

Dynamic pivot tables (transform rows to columns)

答案 1 :(得分:0)

像Orangepill建议的那样,group concat就是这里的答案,但你会将ipiresia结果放在一列:

SELECT am, GROUP_CONCAT(ipiresia)
FROM table
GROUP BY am

你应该有像

这样的东西
+-------+-----------+
|  am   | ipiresia  | 
+-------+-----------+
| 50470 |    29, 43 |
| 50433 |        29 |
|  6417 | 51, 52, 53|
|  4960 |    25, 26 |
|  5567 |        89 |
|  6716 |        88 |
+-------+-----------+