我们说我的桌子看起来像是:
ID | Item | Purchased
17 | Chocolate | 1304
17 | Biscuit | 1209
17 | Jelly | 657
17 | Milk | 2234
我希望它将这些数据动态转换为(列动态增加):
ID | Chocolate_Purchased | Biscuit_Purchased | Jelly_Purchased | Milk_Purchased
17 | 1304 | 1209 | 657 | 2234
如何在MySQL中实现这一目标?我需要处理大量的记录,所以有人可以给我一些有效的方法吗?
答案 0 :(得分:2)
SELECT id,SUM(CASE WHEN Item='Chocolate' THEN Purchased END) as Chocolate_Purchased,
SUM(CASE WHEN Item='Biscuit' THEN Purchased END) as Biscuit_Purchased,
SUM(CASE WHEN Item='Jelly' THEN Purchased END) Jelly_Purchased,
SUM(CASE WHEN Item='Mile' THEN Purchased END) as Mile_Purchased
GROUP BY id
这是动态版
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(IF(t.item = ''',
item,
''', t.purchased, 0)) AS ',
item
)
)INTO @sql
FROM t;
SET @sql = CONCAT('SELECT id,
', @sql, '
FROM t
GROUP BY id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;