使用自连接的方法实现行转列
Posted ooo0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用自连接的方法实现行转列相关的知识,希望对你有一定的参考价值。
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
以上是关于使用自连接的方法实现行转列的主要内容,如果未能解决你的问题,请参考以下文章
SQL Server 动态行转列(参数化表名分组列行转列字段字段值)