【mysql经典题目】行转列

参考:http://www.cnblogs.com/h07061108/p/mysql_questions.html#3806338

 

实现如下效果

 

 

 

CREATE TABLE IF NOT EXISTS tb_amount(
   `Id` INT NOT NULL AUTO_INCREMENT,
   `Year` CHAR(4),
   `Month` CHAR(2),
   `Amount` DECIMAL(5,2),
   PRIMARY KEY(`Id`)
);

INSERT INTO `tb_amount`(`Year`, `Month`, `Amount`) VALUES('1991', '1', '1.1');
INSERT INTO `tb_amount`(`Year`, `Month`, `Amount`) VALUES('1991', '2', '1.2');
INSERT INTO `tb_amount`(`Year`, `Month`, `Amount`) VALUES('1991', '3', '1.3');
INSERT INTO `tb_amount`(`Year`, `Month`, `Amount`) VALUES('1991', '4', '1.4');
INSERT INTO `tb_amount`(`Year`, `Month`, `Amount`) VALUES('1992', '1', '2.1');
INSERT INTO `tb_amount`(`Year`, `Month`, `Amount`) VALUES('1992', '2', '2.2');
INSERT INTO `tb_amount`(`Year`, `Month`, `Amount`) VALUES('1992', '3', '2.3');
INSERT INTO `tb_amount`(`Year`, `Month`, `Amount`) VALUES('1992', '4', '2.4');

SELECT `Year`,
(SELECT Amount FROM   tb_amount m WHERE `Month`=1   AND m.`Year`=tb_amount.`Year`) AS m1,
(SELECT Amount FROM   tb_amount m WHERE `Month`=2   AND m.`Year`=tb_amount.`Year`) AS m2,
(SELECT Amount FROM   tb_amount m WHERE `Month`=3   AND m.`Year`=tb_amount.`Year`) AS m3,
(SELECT Amount FROM   tb_amount m WHERE `Month`=4   AND m.`Year`=tb_amount.`Year`) AS m4
FROM tb_amount  GROUP BY `Year`;

或者



select year,
max(case month when 1 then amount else 0 end ) m1,
max(case month when 2 then amount else 0 end) m2,
max(case month when 3 then amount else 0 end) m3,
max(case month when 4 then amount else 0 end) m4
from tb_amount
group by year;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值