问题
With a MySQL query, how can I take a table like in Example A:
Example A
+------+---------------+----------+
| id | value | class |
+------+---------------+----------+
| 1 | 33.00 | total |
| 1 | 12.00 | shipping |
| 2 | 45.00 | total |
| 2 | 15.00 | shipping |
+------+---------------+----------+
And create a view like Example B?
Example B
+------+---------------+---------------+
| id | value_total | value_shipping|
+------+---------------+---------------+
| 1 | 33.00 | 12.00 |
| 2 | 45.00 | 15.00 |
+------+---------------+---------------+
回答1:
You can simply use SUM()
function for that:
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;
See this SQLFiddle
If you have unknown number of class then try this Dynamic query
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;
Output:
╔════╦═════════════╦════════════════╗
║ ID ║ VALUE_TOTAL ║ VALUE_SHIPPING ║
╠════╬═════════════╬════════════════╣
║ 1 ║ 33 ║ 12 ║
║ 2 ║ 45 ║ 15 ║
╚════╩═════════════╩════════════════╝
See this SQLFiddle
回答2:
try this
select id ,
max(case when class = 'total' then value end) as value_total
, max(case when class = 'shipping' then value end) as value_shipping
from Table1
group by id
DEMO HERE
来源:https://stackoverflow.com/questions/16397666/split-column-values-into-multiple-columns-with-create-view