使用MySQL查询,如何像示例A那样获取表:
Example A +------+---------------+----------+ | id | value | class | +------+---------------+----------+ | 1 | 33.00 | total | | 1 | 12.00 | shipping | | 2 | 45.00 | total | | 2 | 15.00 | shipping | +------+---------------+----------+
并创建一个类似于示例B的视图?
Example B +------+---------------+---------------+ | id | value_total | value_shipping| +------+---------------+---------------+ | 1 | 33.00 | 12.00 | | 2 | 45.00 | 15.00 | +------+---------------+---------------+
您可以简单地使用SUM()函数:
SUM()
SELECT id ,SUM(CASE WHEN class = 'total' THEN value ELSE 0 END) AS value_total ,SUM(CASE WHEN class = 'shipping' THEN value ELSE 0 END) AS value_shipping FROM Table1 GROUP BY id;
如果您的 班级 数目未知,请尝试此动态查询
SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'SUM(case when class = ''', class, ''' then value else 0 end) AS `value_', class, '`' ) ) INTO @sql FROM Table1; SET @sql = CONCAT('SELECT id, ', @sql, ' FROM Table1 GROUP BY id'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
输出:
╔════╦═════════════╦════════════════╗ ║ ID ║ VALUE_TOTAL ║ VALUE_SHIPPING ║ ╠════╬═════════════╬════════════════╣ ║ 1 ║ 33 ║ 12 ║ ║ 2 ║ 45 ║ 15 ║ ╚════╩═════════════╩════════════════╝