Mysql 列转行统计查询 、行转列统计查询

创建表:

-- ----------------------------
-- Table structure for tabname
-- ----------------------------
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 AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tabname
-- ----------------------------
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');
-- ------------------------
-- 查看数据
-- ------------------------
SELECT  * from TabName ;

结果:

Mysql 列转行统计查询 、行转列统计查询_第1张图片

-- ------------------------
-- 列转行统计数据
-- ------------------------
SELECT
	Date,
	MAX(
		CASE NAME
		WHEN '小说' THEN
			Scount
		ELSE
			0
		END
	) 小说,
	MAX(
		CASE NAME
		WHEN '微信' THEN
			Scount
		ELSE
			0
		END
	) 微信
FROM
	TabName
GROUP BY
	Date

结果:

Mysql 列转行统计查询 、行转列统计查询_第2张图片

-- ------------------------
-- 行转列统计数据
-- ------------------------
SELECT
	Date,
	group_concat(NAME, '总量:', Scount) AS b_str
FROM
	TabName
GROUP BY
	Date

结果:

Mysql 列转行统计查询 、行转列统计查询_第3张图片

SELECT
	Date,
	NAME,
	group_concat(NAME, '总量:', Scount) AS b_str
FROM
	TabName
GROUP BY
	Date,
	NAME

结果:

Mysql 列转行统计查询 、行转列统计查询_第4张图片

你可能感兴趣的:(sql)