你可以试试这个查询:
SELECT idA
,GROUP_CONCAT(CASE WHEN idB = 5 THEN val ELSE NULL END) AS `5`
,GROUP_CONCAT(CASE WHEN idB = 6 THEN val ELSE NULL END) AS `6`
,GROUP_CONCAT(CASE WHEN idB = 7 THEN val ELSE NULL END) AS `7`
FROM MyTable
GROUP BY idA
如果您不知道idB
您可以使用此动态查询的数量:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'GROUP_CONCAT(CASE WHEN `idB` = ''',
`idB`,
''' THEN val ELSE NULL END) AS `',
`idB`, '`'
)
) INTO @sql
FROM MyTable;
SET @sql = CONCAT('SELECT idA, ', @sql,'
FROM MyTable
GROUP BY idA
');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
输出:
| IDA | 5 | 6 | 7 |
---------------------------
| 1 | 50 | 0 | (null) |
| 2 | 100 | 12 | 0 |