Skip to content

Instantly share code, notes, and snippets.

@wilpig
Last active March 23, 2017 01:47
Show Gist options
  • Save wilpig/60c54d7ebfb798343e3e4bebf4d5beaa to your computer and use it in GitHub Desktop.
Save wilpig/60c54d7ebfb798343e3e4bebf4d5beaa to your computer and use it in GitHub Desktop.
SQL for a pivot table to join the custom attributes to the primary device row.
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(AttributeID = ''',
AttributeID,
''', Value, NULL)) AS ',
Label
)
) INTO @sql
FROM (SELECT DeviceID, Label, v.Value, v.AttributeID FROM fac_DeviceCustomValue v, fac_DeviceCustomAttribute a WHERE v.AttributeID=a.AttributeID) s;
SET @sql = CONCAT('SELECT d.*, ', @sql, ' FROM fac_DeviceCustomValue v, fac_Device d WHERE v.DeviceID=d.DeviceID GROUP BY v.DeviceID');
PREPARE stmt FROM @sql;
EXECUTE stmt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment