Mysql, reshape data from long / tall to wide

前端 未结 3 784
Happy的楠姐
Happy的楠姐 2020-12-02 23:26

I have data in a mysql table in long / tall format (described below) and want to convert it to wide format. Can I do this using just sql?

Easiest to explain with an

3条回答
  •  忘掉有多难
    2020-12-02 23:54

    Cross-tabs or pivot tables is the answer. From there you can SELECT FROM ... INSERT INTO ... or create a VIEW from the single SELECT.

    Something like:

    SELECT country, 
           MAX( IF( key='President', value, NULL ) ) AS President,
           MAX( IF( key='Currency', value, NULL ) ) AS Currency,
           ...
    
    FROM table 
    GROUP BY country;
    

    For more info: http://dev.mysql.com/tech-resources/articles/wizard/index.html

提交回复
热议问题