group by 多個字段

2021-07-31 07:59:16 字數 2215 閱讀 6010

網上查了很多好像說的都對,但是囉嗦,我看著都費勁

在現實的應用場景中:

如果想要統計每個班的男生/女生的數量就可以group by 班級id,性別

**如下 

select

class.`name`,

(case when students.***=1 then '男' else '女' end) as ***1,

count(students.id)

from

students

left join class on students.classid = class.id

group by class.id,students.***;

具體重現:

1.班級表:

drop table if exists `class`;

create table `class` (

`id` int(11) not null auto_increment comment '班級id',

`name` varchar(250) default null comment '班級名稱',

primary key (`id`)

) engine=innodb auto_increment=3 default charset=utf8 comment='班級表';

-- ----------------------------

-- records of class

-- ----------------------------

insert into `class` values ('1', '一班');

insert into `class` values ('2', '二班');

2.學生表:

drop table if exists `students`;

create table `students` (

`name` varchar(50) default null comment '學習姓名',

`age` int(3) default null comment '學生年齡',

`***` int(1) default null,

`classid` int(11) default null comment '所屬班級id',

`id` int(11) not null auto_increment comment '學生id',

primary key (`id`),

key `fk_reference_1` (`classid`),

constraint `fk_reference_1` foreign key (`classid`) references `class` (`id`)

) engine=innodb auto_increment=11 default charset=utf8 comment='學生資訊表';

-- ----------------------------

-- records of students

-- ----------------------------

insert into `students` values ('姓名11', '15', '1', '1', '3');

insert into `students` values ('姓名12', '16', '2', '1', '4');

insert into `students` values ('姓名13', '15', '1', '1', '5');

insert into `students` values ('姓名21', '15', '1', '2', '8');

insert into `students` values ('姓名22', '15', '2', '2', '9');

insert into `students` values ('姓名23', '15', '2', '2', '10');

3.查詢:

select

class.`name`,

(case when students.***=1 then '男' else '女' end) as ***1,

count(students.id)

from

students

left join class on students.classid = class.id

group by class.id,students.***;

MYSQL 分組 group by 多個字段

sql語法的規定,用了group by,則select之後的字段除聚合函式外都必須出現在group by中,你可以少於group by中的字段,但不能包含group by中沒有的字段 select subject,semester,count from subject selection group...

group by 多個字段查詢結果不對的問題

查詢結果集 查詢限制條件 渠道每日來訪資料 各個渠道在各個日期的來訪使用者合計值,如同一客戶在同一天來訪多次,則計為最後一次來訪的渠道 select count channel name count from select p.id,p.see time p.channel name p.custo...

GROUP BY 兩個字段

create table test a varchar 10 b varchar 10 c int insert into test values a 甲 1 insert into test values a 甲 1 insert into test values a 甲 1 insert int...