常见库函数
AVG 按列求平均值
SUM 按列计算值的总和
MAX 求一列的最大值
MIN 求一列的最大值
COUNT 按列统计个数
排序
desc 降序
asc 升序
代码实现1
--use test1
--create table SC (
--sNo varchar(10) not null,
--cNo varchar(5) not null,
--score numeric(3, 1) )
--use test1
--insert into SC values('S1', 'C1', '90');
--insert into SC values('S1', 'C2', '85');
--insert into SC values('S2', 'C5', '57');
--insert into SC values('S2', 'C6', '80');
--insert into SC values('S2', 'C7', null);
--insert into SC values('S2', 'C4', '70');
--insert into SC values('S3', 'C1', '75');
--insert into SC values('S3', 'C2', '70');
--insert into SC values('S3', 'C4', '85');
--insert into SC values('S4', 'C1', '93');
--insert into SC values('S4', 'C2', '85');
--insert into SC values('S4', 'C3', '83');
--insert into SC values('S5', 'C2', '89');
--select * from SC;
-- 汇总查询
-- 查询数据表SC中学号为S1的学生的总分和平均分
--use test1
--select sum(score) totalScore, AVG(score) avgScore from SC where (sNo = 'S1');
-- 求数据表SC中C1课程号的最高分,最低分和分数差
--use test1
--select max(score) maxScore, min(score) minScore, max(score) - min(score) '[max]-[min]'
--from SC where cNo = 'C1';
--use test1
--create table S (
--sNo varchar(10) not null,
--sN nvarchar(5) not null,
--sex nvarchar(1) not null,
--age int not null,
--dept nvarchar(5) )
--insert into S values('S1', '赵亦', '女', 17, '计算机');
--insert into S values('S2', '钱尔', '男', 18, '信息');
--insert into S values('S3', '孙珊', '女', 20, '信息');
--insert into S values('S4', '李思', '男', 21, '自动化');
--insert into S values('S5', '周武', '男', 19, '计算机');
--insert into S values('S6', '吴丽', '女', 20, '自动化');
求计算机系的学生的总数
-- method 1
-- select count(sNo) allnum from S
-- where dept = '计算机';
-- method 2
-- use test1
-- select count(*) allnum from S
-- where dept = '计算机';
共有多少个系
-- use test1
-- select count(distinct dept) [allDept] from S;
-- 统计有成绩同学的人数
-- use test1
-- select count(distinct sNo) havaScore from SC
-- where score is not null;
-- use test1
-- select * from SC;
-- 查询一共有几门课
use test1
select COUNT(distinct cNo) allClass from SC;
-- 查询每个学生有几个分数
select sNo, count(score) numScore from SC
group by sNo;
-- 分组查询
-- 查询选修两门及以上的学生的学号,姓名和选课门数
use test1
select sNo, count(*) numClass from SC
where cNo <> 'null'
group by sNo
having count(*) >= 2;
-- 排序
-- 查询选修了C1的学生的学号和成绩,安降序排列
select sNo, score from SC endScore
where (cNo = 'c1') order by score desc;
use test1
select sNo, cNo, score from SC
where cNo in ('C2', 'C3', 'C4', 'C5')
order by sNo desc,score desc;
use test1
select sNo, cNo, score from SC
where cNo in ('C2', 'C3', 'C4', 'C5') and sNo = 'S3'
order by sNo desc,score desc;
-- 查询选修了C1课程的学生的学号,姓名,课程号
select S.sNo, sN, cNo from S, SC
where (SC.cNo = 'C1') and (S.sN = SC.sNo);
-- 统计每科课程有多少个学生选
use test1
select cNo, count(*) from SC
group by cNo;
select * from S1;
select id, count(score1) from S1
group by id;
select count(score1) numOfScore1 from S1;