經常使用sql

SELECT
    broswer NAME,
    count(1) VALUE ,
    CASE
WHEN broswer = 'Firefox' THEN '#FF00FF'
WHEN broswer = 'IE' THEN '#FFFF00'
ELSE '#43CD80'
END color
FROM
    t_s_log
GROUP BY
    broswer

 

======================行列轉換=====================
CREATE TABLE `table_name` (
  `id` int(11) NOT NULL,
  `col1` char(2) DEFAULT NULL,
  `col2` char(2) DEFAULT NULL,
  `col3` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;sql

insert into table_name values (1 ,'A1','B1',9), (2 ,'A2','B1',7), (3 ,'A3','B1',4), (4 ,'A4','B1',2),
(5 ,'A1','B2',2), (6 ,'A2','B2',9), (7 ,'A3','B2',8), (8 ,'A4','B2',5), (9 ,'A1','B3',1), (10 ,'A2','B3',8),
(11 ,'A3','B3',8), (12 ,'A4','B3',6), (13 ,'A1','B4',8), (14 ,'A2','B4',2), (15 ,'A3','B4',6), (16 ,'A4','B4',9),
(17 ,'A1','B4',3), (18 ,'A2','B4',5), (19 ,'A3','B4',2), (20 ,'A4','B4',5);code

SELECT
    ifnull(col1, 'total') AS col1,
    sum(IF(col2 = 'B1', col3, 0)) AS B1,
    sum(IF(col2 = 'B2', col3, 0)) AS B2,
    sum(IF(col2 = 'B3', col3, 0)) AS B3,
    sum(IF(col2 = 'B4', col3, 0)) AS B4,
    SUM(col3) AS TOTAL
FROM
    table_name
GROUP BY
    col1 WITH ROLLUP;
table

 

=======================1======================class

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `stu_name` varchar(40) DEFAULT NULL,
  `stu_score` double(20,0) DEFAULT NULL,
  `class_id` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;im


INSERT INTO `student` VALUES ('1', '趙雲', '20', '1');
INSERT INTO `student` VALUES ('2', '張飛', '30', '1');
INSERT INTO `student` VALUES ('3', '關羽', '30', '1');
INSERT INTO `student` VALUES ('4', '劉備', '40', '1');
INSERT INTO `student` VALUES ('5', '曹操', '40', '2');
INSERT INTO `student` VALUES ('6', '許褚', '30', '2');
INSERT INTO `student` VALUES ('8', '荀彧', '28', '2');
INSERT INTO `student` VALUES ('9', '荀攸', '29', '2');
INSERT INTO `student` VALUES ('10', '郭嘉', '24', '2');
INSERT INTO `student` VALUES ('11', '諸葛亮', '39', '1');
INSERT INTO `student` VALUES ('12', '孫權', '40', '3');
INSERT INTO `student` VALUES ('13', '孫權', '38', '3');
INSERT INTO `student` VALUES ('14', '孫堅', '31', '3');
INSERT INTO `student` VALUES ('15', '小喬', '20', '3');
INSERT INTO `student` VALUES ('16', '大橋', '20', '3');
INSERT INTO `student` VALUES ('17', '魯肅', '34', '3');
INSERT INTO `student` VALUES ('18', '陸遜', '31', '3');
INSERT INTO `student` VALUES ('19', '呂蒙', '31', '3');img

SELECT * FROM 
(
    SELECT IFNULL(class_id,'總計') as classid,SUM(stu_score) as score FROM student GROUP BY class_id  WITH ROLLUP
) A
ORDER BY scoretab

相關文章
相關標籤/搜索