码迷,mamicode.com
首页 > 其他好文 > 详细

使用自连接的方法实现行转列

时间:2020-02-02 13:56:56      阅读:53      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!