Select dynamic Columns in mysql

前端 未结 1 344
清酒与你
清酒与你 2020-12-06 13:43

Is it possible to traverse a table like this:

mysql> select * from `stackoverflow`.`Results`;
+--------------+---------+-------------+--------+
| ID           | T         


        
相关标签:
1条回答
  • 2020-12-06 14:19

    Unfortunately MySQL does not have a PIVOT function which is basically what you are trying to do. So you will need to use an aggregate function with a CASE statement:

    SELECT type,
      sum(case when criteria_id = 'env' then result end) env,
      sum(case when criteria_id = 'gas' then result end) gas,
      sum(case when criteria_id = 'age' then result end) age
    FROM results
    group by type
    

    See SQL Fiddle with Demo

    Now if you want to perform this dynamically, meaning you do not know ahead of time the columns to transpose, then you should review the following article:

    Dynamic pivot tables (transform rows to columns)

    Your code would look like this:

    SET @sql = NULL;
    SELECT
      GROUP_CONCAT(DISTINCT
        CONCAT(
          'SUM(IF(CRITERIA_ID = ''',
          CRITERIA_ID,
          ''', RESULT, NULL)) AS ',
          CRITERIA_ID
        )
      ) INTO @sql
    FROM
      Results;
    SET @sql = CONCAT('SELECT type, ', @sql, ' FROM Results GROUP BY type');
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

    See SQL Fiddle with Demo

    0 讨论(0)
提交回复
热议问题