1103简单SQL 行转列思路
转自http://www.cnblogs.com/lhj588/p/3315876.html
-- 经典行列转化
DROP TABLE IF EXISTS TabName;
CREATE TABLE TabName (
Id INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) DEFAULT NULL,
DATE DATE DEFAULT NULL,
Scount INT(11) DEFAULT NULL,
PRIMARY KEY (Id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO TabName VALUES ('1', '小说', '2013-09-01', '10000');
INSERT INTO TabName VALUES ('2', '微信', '2013-09-01', '20000');
INSERT INTO TabName VALUES ('3', '小说', '2013-09-02', '30000');
INSERT INTO TabName VALUES ('4', '微信', '2013-09-02', '35000');
INSERT INTO TabName VALUES ('5', '小说', '2013-09-03', '31000');
INSERT INTO TabName VALUES ('6', '微信', '2013-09-03', '36000');
INSERT INTO TabName VALUES ('7', '小说', '2013-09-04', '35000');
INSERT INTO TabName VALUES ('8', '微信', '2013-09-04', '38000');
INSERT INTO TabName VALUES ('9', '小说', '2013-09-01', '10');
SELECT * FROM TabName;
-- 第零种 列表模式
ID NAME DATE SCOUNT
1 小说 '2013-9-1' 1000
-- 第一种 列表统计模式
SELECT
NAME,DATE,SUM(scount)
FROM TabName
GROUP BY NAME,DATE
-- 第二种 列转为行
DATE 小说 微信
'2013-09-01' 10000 20000
SELECT
DATE,
SUM(CASE WHEN NAME='小说' THEN Scount ELSE 0 END)AS '小说',
SUM(CASE WHEN NAME='微信' THEN Scount ELSE 0 END)AS '微信'
FROM TabName
GROUP BY DATE;
-- 第三种 行转为列
SELECT DATE, GROUP_CONCAT(NAME,'总量:',Scount) AS b_str FROM TabName
GROUP BY DATE;
SELECT DATE,NAME, GROUP_CONCAT(NAME,'总量:',Scount) AS b_str FROM TabName
GROUP BY DATE ,NAME;