由于您没有提到任何 RDBMS,因此此查询将适用于许多 RDBMS。
SELECT MIN(ID) ID,
Place,
MAX(CASE WHEN Type = 'A' THEN count END) A,
MAX(CASE WHEN Type = 'B' THEN count END) B,
MAX(CASE WHEN Type = 'C' THEN count END) C
FROM TableName
GROUP BY Place
如果您有未知数量的Type
.
SELECT GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE WHEN Type = ''',
Type,
''' THEN Count ELSE NULL END) AS ',
CONCAT('`', Type, '`')
)) INTO @sql
FROM TableName;
SET @sql = CONCAT('SELECT MIN(ID) ID,s.Place, ', @sql, '
FROM TableName s
GROUP BY s.Place');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
两个语句的输出
+----+-------+----+----+----+
| ID | PLACE | A | B | C |
+----+-------+----+----+----+
| 1 | Home | 12 | 15 | 16 |
| 4 | Work | 35 | 23 | 55 |
+----+-------+----+----+----+
更新 1
注意:GROUP_CONCAT
结果长度受限于group_concat_max_len系统变量的值,默认值为 1024。因此,如果您有大量列,则可以在使用GROUP_CONCAT
函数之前将该值设置得更高,例如:
SET @@group_concat_max_len = 5000;