MySQL - 行到列我试图搜索帖子,但我只找到了SQL Server / Access的解决方案。我需要一个MySQL(5.X)的解决方案。我有一个表(称为历史)有3列:hostid,itemname,itemvalue。如果我执行select(select * from history),它将返回 +--------+----------+-----------+ | hostid | itemname | itemvalue | +--------+----------+-----------+ | 1 | A | 10 | +--------+----------+-----------+ | 1 | B | 3 | +--------+----------+-----------+ | 2 | A | 9 | +--------+----------+-----------+ | 2 | c | 40 | +--------+----------+-----------+如何查询数据库以返回类似的内容 +--------+------+-----+-----+ | hostid | A | B | C | +--------+------+-----+-----+ | 1 | 10 | 3 | 0 | +--------+------+-----+-----+ | 2 | 9 | 0 | 40 | +--------+------+-----+-----+
3 回答
慕田峪9158850
TA贡献1794条经验 获得超7个赞
SELECT hostid, sum( if( itemname = 'A', itemvalue, 0 ) ) AS A, sum( if( itemname = 'B', itemvalue, 0 ) ) AS B, sum( if( itemname = 'C', itemvalue, 0 ) ) AS C FROM bob GROUP BY hostid;
萧十郎
TA贡献1815条经验 获得超13个赞
另一个选项,如果你有很多需要转动的项目,特别有用的是让mysql为你构建查询:
SELECT GROUP_CONCAT(DISTINCT CONCAT( 'ifnull(SUM(case when itemname = ''', itemname, ''' then itemvalue end),0) AS `', itemname, '`' ) ) INTO @sqlFROM history;SET @sql = CONCAT('SELECT hostid, ', @sql, ' FROM history GROUP BY hostid');PREPARE stmt FROM @sql;EXECUTE stmt;DEALLOCATE PREPARE stmt;
FIDDLE 添加了一些额外的值以使其正常工作
GROUP_CONCAT
默认值为1000,因此如果您有一个非常大的查询,请在运行之前更改此参数
SET SESSION group_concat_max_len = 1000000;
测试:
DROP TABLE IF EXISTS history;
CREATE TABLE history
(hostid INT,
itemname VARCHAR(5),
itemvalue INT);
INSERT INTO history VALUES(1,'A',10),(1,'B',3),(2,'A',9),
(2,'C',40),(2,'D',5),
(3,'A',14),(3,'B',67),(3,'D',8);
hostid A B C D
1 10 3 0 0
2 9 0 40 5
3 14 67 0 8
添加回答
举报
0/150
提交
取消