简体   繁体   中英

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

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
 ( SELECT *
   FROM `day`
   ORDER BY id
   LIMIT 1,2
) AS data;

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]>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM