行转列与CASE.....WHEN...

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- 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=10 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');
INSERT INTO `tabname` VALUES ('9', '微信', '2013-09-01', '30000');

查询结果:

id   Name   Date          Scount
1
小说 2013-09-01 10000 2 微信 2013-09-01 20000 3 小说 2013-09-02 30000 4 微信 2013-09-02 35000 5 小说 2013-09-03 31000 6 微信 2013-09-03 36000 7 小说 2013-09-04 35000 8 微信 2013-09-04 38000 9 微信 2013-09-01 30000

执行:

SELECT 
CASE NAME WHEN '小说' THEN Scount ELSE 0 END  小说,
CASE NAME WHEN '微信' THEN Scount ELSE 0 END  微信 
FROM TabName  
where Date='2013-09-01'

得到:

小说       微信
10000     0
0        20000
0        30000

执行:

SELECT 
SUM(CASE NAME WHEN '小说' THEN Scount ELSE 0 END ) 小说,
SUM(CASE NAME WHEN '微信' THEN Scount ELSE 0 END ) 微信 
FROM TabName  
where Date='2013-09-01'

得到:

小说      微信
10000    50000

执行:

SELECT Date ,
SUM(CASE NAME WHEN '小说' THEN Scount ELSE 0 END ) 小说,
SUM(CASE NAME WHEN '微信' THEN Scount ELSE 0 END ) 微信 
FROM TabName  
GROUP BY Date

得到:

Date      小说    微信
2013
-09-01 10000 50000 2013-09-02 30000 35000 2013-09-03 31000 36000 2013-09-04 35000 38000

 

posted @ 2017-04-22 13:33  soar_hu  阅读(306)  评论(0编辑  收藏  举报