问题描述:
表信息为:
create table SC(SID tinyint,CID tinyint,score tinyint)charset utf8;
set names gbk;
insert into SC
values(01,01,80),(01,02,90),(01,03,99),(02,01,70),(02,02,60),
(02,03,80),(03,03,80),(04,01,50),(04,02,30),(04,03,20),
(05,01,76),(05,02,87),(06,03,34),(07,02,89),(07,03,98),
(03,01,80),(03,02,80),(06,01,31);
需要查找:按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩
sql语句
select Sid,max(case Cid when '1' thenscore else 0 end)'01',
max(case Cid when '2' then score else 0end)'02',
max(case Cid when '3' then score else 0end)'03',AVG(score)平均分 from SC
groupby Sid order by平均分desc ;
不加max()函数的sql语句:
select Sid,(case Cid when '1' then scoreelse 0 end)'01',
(case Cid when '2' then score else 0end)'02',
(case Cid when '3' then score else 0end)'03',AVG(score)平均分 from SC
group by Sid order by 平均分 desc ;
以上两个SQL语句有什么区别吗?
解决方法:
max()函数检索的是每个学生每个科目的分数,不加max()函数检索的是每个学生按原数据表中的顺序的第一个科目的分数
case when实现行列转换时会出现多条记录,如果不用聚合函数直接进行group by分组,那么检索的是基表里分组字段的第一条记录,
如果使用max()函数之后再进行group by分组,那么就会检索每个字段的最大值然后再分组








暂无数据