#行转列 id 和课程
select stu_id , '语文' as '课程', count_chinese as '分数' from student
union
select stu_id , '数学' as '课程', count_math as '分数' from student
union
select stu_id , '英语' as '课程', count_english as '分数' from student
#查看课程的及格数目
select
sum(case when count_chinese>=60 then 1 else 0 end) 语文,
sum(case when count_math>=60 then 1 else 0 end) 数学,
sum(case when count_english>=60 then 1 else 0 end) 英语
from student
#统计stu_family表的各省人数 PostgreSQL和MySQL中可以这样写,原因是他们会先检查select语句
#select case
# when stu_address='徐州' then '江苏'
# when stu_address='无锡' then '江苏'
# when stu_address='杭州' then '浙江'
# when stu_address='乌鲁木齐' then '新疆'
# when stu_address='哈尔滨' then '黑龙江'
# when stu_address='广州' then '广东'
# when stu_address='南京' then '江苏'
# else '其它'
# end 地区,
# sum(stu_peoples) 人数
#from stu_family
#group by 地区;
#统计stu_family表的各省人数
select case
when stu_address='徐州' then '江苏'
when stu_address='无锡' then '江苏'
when stu_address='杭州' then '浙江'
when stu_address='乌鲁木齐' then '新疆'
when stu_address='哈尔滨' then '黑龙江'
when stu_address='广州' then '广东'
when stu_address='南京' then '江苏'
else '其它'
end '地区',
sum(stu_peoples) as '人数'
from stu_family
group by case
when stu_address='徐州' then '江苏'
when stu_address='无锡' then '江苏'
when stu_address='杭州' then '浙江'
when stu_address='乌鲁木齐' then '新疆'
when stu_address='哈尔滨' then '黑龙江'
when stu_address='广州' then '广东'
when stu_address='南京' then '江苏'
else '其它' end;
#更改数据
update stu_family set stu_peoples=5 where stu_id=2
#增加字段
alter table stu_family add stu_peoples int
#插入数据
insert into stu_family(stu_number, stu_address) values
(1,'徐州'),
(2,'无锡'),
(3,'杭州'),
(4,'乌鲁木齐'),
(5,'哈尔滨'),
(6,'广州'),
(7,'南京');
#添加一张表
create table stu_family
(
stu_id int primary key auto_increment,#主键自增
stu_address varchar(30),
stu_phone varchar(15),
stu_number int unique #唯一值
)
#设置自增
alter table student modify stu_id int auto_increment
#设置唯一值
alter table student add unique (stu_number)
#添加字段
alter table student add
(
stu_number int
)
#case判断单项
select stu_id '学号', count_math '数学',
case
when count_math>=99 then 'S'
when count_math>=90 then 'A'
when count_math>=75 then 'B'
when count_math>=60 then 'C'
else '不及格'
end '等级'
from student