Is it possible to traverse a table like this:
mysql> select * from `stackoverflow`.`Results`; +--------------+---------+-------------+--------+ | ID | T
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