Sunil Dabhi Sunil Dabhi - 4 months ago 19
MySQL Question

MySQL pivot row to column dynamically

i have table:day

id | jour
1 Lundi 01 Août 2016
2 Mardi 02 Août 2016
3 Mercredi 03 Août 2016
4 Jeudi 04 Août 2016


there will be 50 rows i want output like:

Lundi 01 Août 2016 Mardi 02 Août 2016 Mercredi 03 Août 2016
1 2 3

Answer

you can do it easy with this queries: first generate the query and then execute it as prepared statement.

SET SESSION group_concat_max_len = 1000000;

SELECT
  CONCAT('SELECT ',
    GROUP_CONCAT(
      CONCAT (
        "MAX(IF(`jour` = '",jour,'\',id,NULL)) AS `',jour,'`'
      )
    ),
    ' FROM `day`'
  ) INTO @SQL
FROM `day`;

select @SQL;  -- see the query only for debug

PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

sample

MariaDB [yourSchema]> select * from day;
+----+------------------------+
| id | jour                   |
+----+------------------------+
|  1 | Lundi 01 Août 2016     |
|  2 | Mardi 02 Août 2016     |
|  3 | Mercredi 03 Août 2016  |
|  4 | Jeudi 04 Août 2016     |
+----+------------------------+
4 rows in set (0.00 sec)

MariaDB [yourSchema]> SELECT
    ->   CONCAT('SELECT ',
    ->     GROUP_CONCAT(
    ->       CONCAT (
    ->         "MAX(IF(`jour` = '",jour,'\',id,NULL)) AS `',jour,'`'
    ->       )
    ->     ),
    ->     ' FROM `day`'
    ->   ) INTO @SQL
    -> FROM `day`;
Query OK, 1 row affected (0.00 sec)

MariaDB [yourSchema]> PREPARE stmt FROM @SQL;
Query OK, 0 rows affected (0.00 sec)
Statement prepared

MariaDB [yourSchema]> EXECUTE stmt;
+---------------------+---------------------+------------------------+---------------------+
| Lundi 01 Août 2016  | Mardi 02 Août 2016  | Mercredi 03 Août 2016  | Jeudi 04 Août 2016  |
+---------------------+---------------------+------------------------+---------------------+
|                   1 |                   2 |                      3 |                   4 |
+---------------------+---------------------+------------------------+---------------------+
1 row in set (0.00 sec)

MariaDB [yourSchema]> DEALLOCATE PREPARE stmt;
Query OK, 0 rows affected (0.00 sec)

MariaDB [yourSchema]>
Comments