标签:value code prim http 行转列 img inf alt efault
CREATE TABLE `user_kills` ( `id` int(11) NOT NULL, `user_id` int(11) DEFAULT NULL, `timestr` datetime DEFAULT NULL, `kills` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `user_kills` VALUES (‘1‘, ‘2‘, ‘2020-01-10 00:00:00‘, ‘10‘); INSERT INTO `user_kills` VALUES (‘2‘, ‘2‘, ‘2020-02-01 00:00:00‘, ‘2‘); INSERT INTO `user_kills` VALUES (‘3‘, ‘2‘, ‘2020-02-05 00:00:00‘, ‘12‘); INSERT INTO `user_kills` VALUES (‘4‘, ‘4‘, ‘2020-01-10 00:00:00‘, ‘3‘); INSERT INTO `user_kills` VALUES (‘5‘, ‘2‘, ‘2020-02-11 00:00:00‘, ‘5‘); INSERT INTO `user_kills` VALUES (‘6‘, ‘2‘, ‘2020-01-06 00:00:00‘, ‘1‘); INSERT INTO `user_kills` VALUES (‘7‘, ‘3‘, ‘2020-01-11 00:00:00‘, ‘20‘); INSERT INTO `user_kills` VALUES (‘8‘, ‘2‘, ‘2020-02-12 00:00:00‘, ‘10‘); INSERT INTO `user_kills` VALUES (‘9‘, ‘2‘, ‘2020-02-07 00:00:00‘, ‘17‘);
使用自连接的方法实现行转列:
SELECT * FROM ( SELECT sum(k.kills) as ‘猪八戒‘ FROM user_kills k WHERE k.user_id = 2 ) a CROSS JOIN( SELECT sum(k.kills) as ‘孙悟空‘ FROM user_kills k WHERE k.user_id = 3 ) b CROSS JOIN( SELECT sum(k.kills) as ‘沙悟净‘ FROM user_kills k WHERE k.user_id = 4 ) c
使用CASE方法实现行转列:
SELECT sum(case when user_id = 2 then k.kills end) as ‘猪八戒‘, sum(case when user_id = 3 then k.kills end) as ‘孙悟空‘, sum(case when user_id = 4 then k.kills end) as ‘沙悟净‘ FROM user_kills k
标签:value code prim http 行转列 img inf alt efault
原文地址:https://www.cnblogs.com/ooo0/p/12251748.html