Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

求教简单分组并统计总和查询sql

现有数据表

积分记录 points_log  
id  name   sex  points      date
1   张三    男     1     2020-11-1  
2   张三    男     2     2020-11-1        
3   李四    女     4     2020-11-1
4   王五    女     6     2020-11-1

mysql需要统计为这样的格式

  date    总人数  总积分  男人数 女人数  男性积分   女性积分 
2020-11-1   3      13      1      2      3         10      

测试表结构

CREATE TABLE `points_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) DEFAULT NULL,
  `sex` varchar(6) DEFAULT NULL,
  `points` int(10) DEFAULT NULL,
  `date` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

INSERT INTO `points_log` VALUES (1, '张三', '男', 1, '2020-11-1');
INSERT INTO `points_log` VALUES (2, '张三', '男', 2, '2020-11-1');
INSERT INTO `points_log` VALUES (3, '李四', '女', 4, '2020-11-1');
INSERT INTO `points_log` VALUES (4, '王五', '女', 6, '2020-11-1');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

自己已经解决

SELECT
    count( NAME ) total_people,
    sum( points ) points,
    sum(
    IF
    ( sex = '男', 1, 0 )) male_count,
    sum(
    IF
    ( sex = '女', 1, 0 )) female_count,
    sum(
    IF
    ( sex = '男', points, 0 )) male_points,
    sum(
    IF
    ( sex = '女', points, 0 )) female_points 
FROM
    ( SELECT date, NAME, sex, sum( points ) points FROM points_log GROUP BY date, NAME, sex )t

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...