user2726889 user2726889 - 7 months ago 20
SQL Question

MySql Prepared Statement to Convert Row Values to Columns

I'm trying to follow the example from this site:
http://vitobotta.com/mysql-generate-column-names-dynamically-from-row-values/

I have a table with like this:

+------------+--------------+----------+-------------+
| MessageId | ProcessDate | FieldName | FieldValue |
+------------+--------------+-----------+------------+
| 18 | 2015-12-04 | data | 101110101 |
| 18 | 2015-12-04 | type | binary |
| 19 | 2015-12-04 | type | integer |
| 19 | 2015-12-04 | data | 34 |
+------------+--------------+-----------+------------+


What I want is something like this:

+------------+--------------+----------+-------------+
| MessageId | ProcessDate | type | data |
+------------+--------------+-----------+------------+
| 18 | 2015-12-04 | binar | 101110101 |
| 19 | 2015-12-04 | integer | 34 |
+------------+--------------+-----------+------------+


My Code:

DROP TABLE IF EXISTS tmp_results;

CREATE TEMPORARY TABLE tmp_results AS
SELECT r.`MessageId`, r.`ProcessDate`, r.`TransportType`, d.`FieldName`, d.`FieldValue`
FROM
returnmessages r, decodedmessagessummaryrecord s, decodedmessagesdetailrecord d
WHERE r.`Id` = s.`ReturnMessagesId`
AND s.`Id` = d.`DecodedMessagesSummaryRecordId`
AND r.`MobileId` = "35"
LIMIT 10;

SELECT CONCAT('
SELECT MessageId, ProcessDate, TransportType, ', field_value, '
FROM tmp_results'
)
INTO @variable1
FROM
(SELECT GROUP_CONCAT(CONCAT('IFNULL(MAX(CASE WHEN FieldName=''',field_name,''' THEN FieldValue
END), ''-'' AS "', col_name,'"')) field_value
FROM(
SELECT field_name, field_name as col_name
FROM(SELECT DISTINCT FieldName AS field_name FROM tmp_results) AS fieldnames
) field_with_col_names
) result;
PREPARE prepstate FROM @s;

EXECUTE prepstate;

DEALLOCATE PREPARE prepstate;


Which returns an error:


Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tmp_results' at line 3


I'm not really sure what's going wrong at this point.

Answer
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when FieldName = ''',
      FieldName,
      ''' then FieldValue  end) AS ',
      '`',FieldName,'`'
    )
  ) INTO @sql
from tmp_results;

SET @sql = CONCAT('SELECT MessageId, ProcessDate, TransportType, ', @sql, ' from tmp_results 
group by MessageId');

SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

FIDDLE