The only way I know of doing this exclusively with SQL would be something like this:
SELECT
CONCAT (
'SELECT name, ',
GROUP_CONCAT(
DISTINCT CONCAT(
'(',
'SELECT IFNULL(SUM(value), 0) '
'FROM tabela b ',
'WHERE b.key_id = "', key_id, '"',
'AND b.name = a.name'
') ', key_id, ' '
)
), ' '
'FROM tabela a ',
'GROUP BY name'
) INTO @sql
FROM tabela;
PREPARE stmt FROM @sql;
EXECUTE stmt;
Notice that there are 3 statements (the first generates a query, the second "prepares" the statement, and the third executes the query).
Although this works, I would only recommend using this if it is to generate a report, or for a very small database, never in an application, because for a few hundred key_ids, the DB would not swallow well. >
The best solution would be to get all the data from the table and group it according to what you need on the application side (using node / PHP / C # / Java, whatever).