欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mysql 列转行

程序员文章站 2024-03-01 18:06:52
...
/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50528
Source Host           : localhost:3306
Source Database       : test

Target Server Type    : MYSQL
Target Server Version : 50528
File Encoding         : 65001

Date: 2020-03-31 17:30:23
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for my_test
-- ----------------------------
DROP TABLE IF EXISTS `my_test`;
CREATE TABLE `my_test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `year` int(11) DEFAULT NULL,
  `jidu` int(11) DEFAULT NULL,
  `month` int(11) DEFAULT NULL,
  `money` int(11) DEFAULT NULL,
  `type` varchar(255) DEFAULT NULL,
  `subtype` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of my_test
-- ----------------------------
INSERT INTO `my_test` VALUES ('1', '2019', '1', '1', '1', 'type1', 'type1_sub');
INSERT INTO `my_test` VALUES ('2', '2019', '1', '2', '1', 'type1', 'type1_sub');
INSERT INTO `my_test` VALUES ('3', '2020', '1', '1', '10', 'type1', 'type1_sub');
INSERT INTO `my_test` VALUES ('4', '2020', '2', '4', '10', 'type1', 'type1_sub');
INSERT INTO `my_test` VALUES ('5', '2020', '1', '1', '10', 'type1', 'type1_sub2');
INSERT INTO `my_test` VALUES ('6', '2020', '1', '1', '10', 'type2', 'type1_sub');
INSERT INTO `my_test` VALUES ('7', '2020', '1', '1', '1', 'type2', 'type1_sub2');
INSERT INTO `my_test` VALUES ('20', '2019', '1', '1', '1', 'type1', 'type1_sub');
SELECT type,subtype,
sum(CASE WHEN (year = 2019 and jidu=1 and month=1) THEN num ELSE 0 END) as '2019Q1-Jan',
sum(CASE WHEN (year = 2019 and jidu=1 and month=2) THEN num ELSE 0 END) as '2019Q1-Feb',
sum(CASE WHEN (year = 2020 and jidu=1 and month=1) THEN num ELSE 0 END) as '2020Q1-Jan',
sum(CASE WHEN (year = 2020 and jidu=2 and month=4) THEN num ELSE 0 END) as '2020Q2-Apri'
FROM 
(select type,subtype,year,jidu,month,count(*) as num from my_test where 1=1 GROUP BY type,subtype,year,jidu,month) a
 GROUP BY type,subtype
相关标签: SQL