微学网

热门关键词:   as  thinkphp  ecshop  xxx  商务通  www.ymwears.cn
热门: ASP.NET PHP编程 ASP编程 JSP编程 Python

数据库——SQL语法练习

发布时间:2021-05-04 来源:未知 点击:

文章目录

  • 1. 构建数据库
  • 2. 练习题

1. 构建数据库

  • 学生student表:
学生编号 学生名称 学生年纪    学生性别
  s_id  s_name  s_age       s_sex   
------  ------  ----------  --------
     1  赵雷      1990-01-01       
     2  钱电      1990-12-21       
     3  孙风      1990-05-20       
     4  李云      1990-08-06       
     5  周梅      1991-12-01       
     6  吴兰      1992-03-01       
     7  郑竹      1989-07-01       
     8  王菊      1990-01-20     
  • 科目course表:
课程编号 课程名称  教师编号
  c_id  c_name    t_id  
------  ------  --------
     1  英语             2
     2  语文             3
     3  数学             1
     4  物理             1
  • 教师teacher表:
教师编号 教师名称
  t_id  t_name     
------  -----------
     1  张老师  
     2  王老师  
     3  李老师  
  • 成绩score表:
		成绩		学生编号 课程编号
 s_id  s_score  stu_id  cou_id  
------  -------  ------  --------
     1       98       1         1
     2       95       1         2
     3       97       1         3
     4       92       2         1
     5       86       2         2
     6       99       2         3
     7		 89		  2         4     
     8       83       3         1
     9       91       3         2
    10       92       3         3
    11       75       4         1
    12       83       4         2
    13       81       4         3
    14       84       5         1
    15       92       5         2
    16       87       5         3
    17		 97       5			4
    18       69       6         1
    19       77       6         2
    20       77       7         1
    21       85       7         3
    22       93       8         2
  • sql
CREATE DATABASE IF NOT EXISTS test_sql;
USE test_sql;
CREATE TABLE IF NOT EXISTS student(
	s_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
	s_name NVARCHAR(10) NOT NULL,
	s_age DATE NOT NULL,
	s_sex NVARCHAR(10) NOT NULL,
	PRIMARY KEY(s_id)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO student VALUES(0, N'赵雷', '1990-01-01', N'男'), (0, N'钱电', '1990-12-21', N'男'),
(0, N'孙风', '1990-05-20', N'男'), (0, N'李云', '1990-08-06', N'男'),
(0, N'周梅', '1991-12-01', N'女'), (0, N'吴兰', '1992-03-01', N'女'),
(0, N'郑竹', '1989-07-01', N'女'), (0, N'王菊', '1990-01-20', N'女');

CREATE TABLE IF NOT EXISTS course(
	c_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
	c_name NVARCHAR(10) NOT NULL,
	t_id INT UNSIGNED,
	PRIMARY KEY(c_id)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO course VALUES(0, N'英语', 2), (0, N'语文', 3), (0, N'数学', 1), (0, N'物理', 1);

CREATE TABLE IF NOT EXISTS teacher(
	t_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
	t_name NVARCHAR(10) NOT NULL,
	PRIMARY KEY(t_id)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO teacher VALUES(0, N'张老师'), (0, '王老师'), (0, '李老师');

CREATE TABLE IF NOT EXISTS score(
	s_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
	s_score TINYINT,
	stu_id INT UNSIGNED,
	cou_id INT UNSIGNED,
	PRIMARY KEY(s_id)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO score VALUES
(0, 98, 1, 1), (0, 95, 1, 2), (0, 97, 1, 3),
(0, 92, 2, 1), (0, 86, 2, 2), (0, 99, 2, 3), (0, 89, 2, 4),
(0, 83, 3, 1), (0, 91, 3, 2), (0, 92, 3, 3),
(0, 75, 4, 1), (0, 83, 4, 2), (0, 81, 4, 3),
(0, 84, 5, 1), (0, 92, 5, 2), (0, 87, 5, 3), (0, 97, 5, 4),
(0, 69, 6, 1), (0, 77, 6, 2), 
(0, 77, 7, 1),  			  (0, 85, 7, 3),
 			   (0, 93, 8, 2);				 

2. 练习题

  • 【1】:查询【课程1】比【课程2】成绩高的学生编号和学生姓名和【课程1】、【课程2】的分数
# 如果【课程1】、【课程2】成绩都存在,正常比较
# 如果【课程2】成绩不存在,【课程1】比【课程2】成绩高
SELECT s.s_id, s.s_name, a.s_score score1, b.s_score score2
FROM student s
LEFT JOIN (SELECT stu_id, s_score FROM score WHERE cou_id = 1) a
ON s.s_id = a.stu_id
LEFT JOIN (SELECT stu_id, s_score FROM score WHERE cou_id = 2) b
ON s.s_id = b.stu_id 
WHERE b.s_score IS NULL OR a.s_score > b.s_score
  • 【2】:查询平均成绩大于等于 80 分的同学的学生编号和学生姓名和平均成绩
# 有几门就比较几门成绩
SELECT s.s_id, s.s_name, a.avg_score
FROM student s
LEFT JOIN (SELECT stu_id, AVG(s_score) avg_score FROM score GROUP BY stu_id) a
ON s.s_id = a.stu_id
WHERE a.avg_score > 80

# grouo by中使用having
SELECT st.s_id, st.s_name, AVG(sc.s_score) avg_score
FROM student st
LEFT JOIN score sc
ON st.s_id = sc.stu_id
GROUP BY st.s_id, st.s_name HAVING AVG(sc.s_score) > 80
  • 【3】:查询score表上存在至少一门成绩的学生信息
SELECT * 
FROM student
WHERE s_id IN (SELECT DISTINCT stu_id FROM score WHERE s_score IS NOT NULL)
  • 【3.1】:查询score表上存在至少2门成绩的学生信息
SELECT st.s_id, st.s_name 
FROM student st
LEFT JOIN (SELECT stu_id, COUNT(s_score) size FROM score GROUP BY stu_id) s
ON st.s_id = s.stu_id
WHERE s.size > 1; 
  • 【4】:查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩
# 没成绩的显示为 null 
SELECT st.s_id, st.s_name, COUNT(sc.cou_id) AS '选课总数', SUM(sc.s_score) AS '总成绩'  
FROM student st
LEFT JOIN score sc
ON st.s_id = sc.stu_id
GROUP BY st.s_id

# 没成绩的显示为 0
SUM(case when sc.s_score is null then 0 else sc.s_score) AS '总成绩'
  • 【5】:查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩(没成绩的显示为 null )、每门课程成绩
# 使用聚合函数 + case when,避免将cou_id、s_score等字段放在group by 中
SELECT st.s_id, st.s_name, COUNT(*) AS 选课总数, SUM(sc.s_score) AS 总成绩,
	SUM(CASE WHEN sc.cou_id = 1 THEN sc.s_score ELSE NULL END) AS score1,
	SUM(CASE WHEN sc.cou_id = 2 THEN sc.s_score ELSE NULL END) AS score2,
	SUM(CASE WHEN sc.cou_id = 3 THEN sc.s_score ELSE NULL END) AS score3
FROM student st, score sc
WHERE st.s_id = sc.stu_id
GROUP BY st.s_id, st.s_name

# 这种方式需要额外对 s_name 、s_score 添加索引,否则很慢
SELECT st.s_id, st.s_name, SUM(sc.s_score) AS sumscore, sc.s_score AS score1, sc2.s_score AS score2, sc3.s_score AS score3
FROM student st
LEFT JOIN score sc
ON st.s_id = sc.`stu_id`
LEFT JOIN score sc2
ON st.s_id = sc2.`stu_id`
LEFT JOIN score sc3
ON st.s_id = sc3.stu_id 
WHERE sc.`cou_id` = 1 AND sc2.cou_id = 2 AND sc3.cou_id = 3
GROUP BY st.`s_id`, st.s_name, sc.s_score, sc2.s_score, sc3.s_score
  • 【6】:查询指定老师的数量
# ’李‘姓
SELECT COUNT(*) AS con 
FROM teacher
WHERE t_name LIKE '李%'

# 名字中带’老‘
WHERE t_name LIKE '%老%'

# 要求不同名的老师
SELECT COUNT(distinct t_name) AS con
  • 【7】:查询没学过「李老师」任意课程的同学的信息 (李老师只教一门课程)
# 思路1
SELECT * FROM student WHERE s_id NOT IN(
	SELECT stu_id FROM score WHERE s_score IS NOT NULL AND cou_id IN (
		SELECT c_id FROM course WHERE t_id = (
			SELECT t_id FROM teacher WHERE t_name = '李老师')))

# 思路2:构造表 学号、课程号、成绩、教师编号、教师姓名,依据教师姓名查询学生信息
SELECT st.* 
FROM student st
WHERE st.s_id NOT IN(
	SELECT sc.stu_id
	FROM score sc
	INNER JOIN course c # inner join只取都存在的字段,即排除null
	ON sc.cou_id = c.c_id
	INNER JOIN teacher t
	ON c.t_id = t.t_id
	WHERE t.t_name = '李老师'
)
  • 【8】:查询没学过「张老师」任意课程的同学的信息 (张老师教多门课程)
# 最直接的思路:查张老师教哪些课程,学过这些课程(包括学过一门的)的学生信息有哪些,排除掉这些学生
SELECT DISTINCT s_id 
FROM student
WHERE s_id NOT IN(
	SELECT stu_id
	FROM score
	WHERE cou_id IN(
		SELECT c_id
		FROM course
		WHERE t_id = (
			SELECT t_id
			FROM teacher
			WHERE t_name = "张老师"
		)
	)
)
  • 【9】:查询学过「张老师」全部课程的同学的信息(张老师教多门课程)
SELECT stu_id
FROM score
WHERE cou_id IN (
	SELECT a.c_id
	FROM course a
	INNER JOIN teacher b
	ON a.t_id = b.t_id
	WHERE b.t_name = "张老师"
)
GROUP BY stu_id HAVING COUNT(DISTINCT cou_id) = (
	SELECT COUNT(c_id) 
	FROM course c 
	INNER JOIN teacher t 
	ON c.t_id = t.t_id 
	WHERE t.t_name = '张老师'
)
  • 【10】:查询学过编号为"1"并且也学过编号为"2"的课程的同学的信息
# 使用子查询,将两张表取交集
SELECT * 
FROM student 
WHERE s_id IN (
	SELECT a.stu_id
	FROM (SELECT stu_id FROM score WHERE cou_id = 1) AS a
	INNER JOIN (SELECT stu_id FROM score WHERE cou_id = 2) AS b
	ON a.stu_id = b.stu_id
)
  • 【11】:查询某个课程编号的总成绩、平均成绩、选课人数
SELECT cou_id, SUM(s_score), AVG(s_score), COUNT(stu_id) FROM score
group by cou_id having cou_id = 2
  • 【12】:查询所有课程成绩都小于80分的学生信息(对比题目【2】)
# 思路1:统计小于80分的课程个数是否等于学过的全部课程个数,取交集
SELECT st.* FROM student st
INNER JOIN ( 	
	SELECT stu_id, COUNT(cou_id) AS cnt
	FROM score 
	WHERE s_score < 80
	GROUP BY stu_id
) AS a
ON st.s_id = a.stu_id
INNER JOIN (
	SELECT stu_id, COUNT(cou_id) AS cnt
	FROM score
	GROUP BY stu_id
) AS b
ON a.stu_id = b.stu_id
WHERE a.cnt = b.cnt

# 思路2:最高成绩小于80分
SELECT st.* 
FROM student st
INNER JOIN score sc
ON st.s_id = sc.stu_id
GROUP BY sc.stu_id HAVING MAX(sc.s_score) < 80	
  • 【13】:查询没有学全所有课程的同学的信息
SELECT st.s_id
FROM student st
LEFT JOIN score AS sc
ON st.s_id = sc.stu_id
GROUP BY st.s_id HAVING COUNT(DISTINCT sc.cou_id) < (SELECT COUNT(DISTINCT c_id) FROM course)	
  • 【14】:查询和学号为" 1 "的同学学习的课程至少有一门相同的其他同学的信息
# 使用group by去重 having筛选
SELECT * 
FROM student 
WHERE s_id IN (			
	SELECT stu_id 
	FROM score 
	WHERE cou_id IN(
		SELECT cou_id 
		FROM score 
		WHERE stu_id = 1
	)
	GROUP BY stu_id HAVING stu_id != 1
)

# 使用distinct去重
SELECT * 
FROM student 
WHERE s_id IN (			
	SELECT DISTINCT stu_id 
	FROM score 
	WHERE cou_id IN(
		SELECT cou_id 
		FROM score 
		WHERE stu_id = 1
	) AND stu_id != 1	
)

# 使用inner join代替in,适合数据量大的场景
SELECT a.s_id, a.s_name 
FROM student a
INNER JOIN (			
	SELECT DISTINCT stu_id 
	FROM score c
	INNER JOIN(
		SELECT cou_id 
		FROM score 
		WHERE stu_id = 1
	) d
	ON c.cou_id = d.cou_id
	WHERE stu_id != 1	
) b
ON a.s_id = b.stu_id
  • 【15】:查询和学号为" 1 "号的同学学习的课程完全相同的其他同学的信息
# 思路1
SELECT * 
FROM student 
WHERE s_id IN (
	# 学习课程数量 = 01号同学学习课程数量
	SELECT stu_id 
	FROM score 
	WHERE s_id != 1 
	GROUP BY stu_id 
	HAVING COUNT(DISTINCT cou_id) = (
		SELECT COUNT(DISTINCT cou_id) FROM score WHERE stu_id = 1
	)

)
AND s_id NOT IN (
	# 排除学习课程和01号同学不一致的情况
	SELECT DISTINCT stu_id 
	FROM score
	WHERE cou_id NOT IN (
		SELECT cou_id FROM score WHERE stu_id = 1	
	)
)

# 思路2:使用GROUP_CONCAT将数据压缩到一行
SELECT s.*
FROM student s, score sc1
WHERE s.s_id = sc1.stu_id AND sc1.stu_id <> '01'
GROUP BY s.s_id
HAVING GROUP_CONCAT(sc1.cou_id ORDER BY cou_id) = (
	SELECT GROUP_CONCAT(cou_id ORDER BY cou_id)
	FROM score sc2
	WHERE sc2.stu_id = '01'
	GROUP BY sc2.stu_id
)
  • 【16】:查询两门及以上成绩低于80分的同学的学号,姓名及其平均成绩
# 思路:查询成绩小于80分的 -- 分组,count两门及以上 -- 查姓名 join student表
SELECT a.s_id, a.s_name, b.avg_score FROM student a
INNER JOIN(
	SELECT stu_id, AVG(s_score) avg_score
	FROM score
	WHERE s_score < 80
	GROUP BY stu_id 
	HAVING COUNT(DISTINCT cou_id) >= 2
) b
ON a.s_id = b.stu_id
  • 【17】:检索" 01 "课程分数大于80,按分数降序排列的学生信息
SELECT st.s_name, sc.s_score
FROM student st
INNER JOIN score sc
ON st.s_id = sc.stu_id
WHERE sc.cou_id = 1 AND sc.s_score > 80	
ORDER BY sc.s_score DESC
  • 【18】:按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩
# 如果不要求列出所有课程的成绩
SELECT a.s_id, a.s_name, b.avg_score
FROM student a
INNER JOIN (
	SELECT stu_id, AVG(s_score) AS avg_score
	FROM score 
	GROUP BY stu_id
) b
ON a.s_id = b.stu_id
ORDER BY b.avg_score DESC

# 要求列出所有课程的成绩
SELECT a.s_id "学号", a.s_name "姓名", b.score1 "语文", b.score2 "数学", b.score3 "英语", b.avg_score "平均成绩"
FROM student a
INNER JOIN (
	SELECT stu_id, AVG(s_score) AS avg_score,
		MAX(CASE WHEN cou_id = 2 THEN s_score ELSE NULL END) score1,
		MAX(CASE WHEN cou_id = 3 THEN s_score ELSE NULL END) score2,
		MAX(CASE WHEN cou_id = 1 THEN s_score ELSE NULL END) score3
	FROM score 
	GROUP BY stu_id
) b
ON a.s_id = b.stu_id
ORDER BY b.avg_score DESC
  • 【19】:查询各科成绩最高分、最低分和平均分:

以如下形式显示:课程 ID,课程 name,最高分,最低分,平均分,及格率,中等率,优良率,优秀率
及格为>=60,中等为:70-80,优良为:80-90,优秀为:>=90
要求输出课程号和选修人数,查询结果按人数降序排列,若人数相同,按课程号升序排列

# 用sum代替count,符合条件 then 加 1
SELECT a.cou_id "编号", b.c_name "科目", MAX(a.s_score) "最高分", MIN(a.s_score) AS "最低分", AVG(a.s_score) AS "平均分",
	SUM(CASE WHEN a.s_score >= 90 AND a.s_score < 100 THEN 1 ELSE 0 END) / COUNT(a.stu_id) "优秀率",
	SUM(CASE WHEN a.s_score >= 80 AND a.s_score < 90 THEN 1 ELSE 0 END) / COUNT(a.stu_id) "良好率",
	SUM(CASE WHEN a.s_score >= 70 AND a.s_score < 80 THEN 1 ELSE 0 END) / COUNT(a.stu_id) "中等率",
	SUM(CASE WHEN a.s_score >= 60 AND a.s_score < 70 THEN 1 ELSE 0 END) / COUNT(a.stu_id) "及格率"
FROM score a
INNER JOIN course b
ON b.c_id = a.cou_id
GROUP BY a.cou_id
  • 【20】:按各科成绩进行排序,并显示排名
# 窗口函数的使用:row_number() dense_number() rank()
# row_number() 没有重复值的排序
分数 排名
80   1
75   2
75   3
60   4
# dense_number() 连续排序
分数 排名
80   1
75   2
75   2
60   3
# rank() 跳跃排序
分数 排名
80   1
75   2
75   2
60   4
SELECT a.s_id "编号", b.s_name "姓名", c.c_name "科目", a.s_score "成绩", 
	rank() over(PARTITION BY a.cou_id ORDER BY a.s_score DESC) AS "排名"
FROM score a
INNER JOIN student b
ON a.stu_id = b.s_id
INNER JOIN course c
ON a.cou_id = c.c_id
  • 【21】:查询学生的总成绩,并进行排名
SELECT stu_id, SUM(s_score) total, rank() over(ORDER BY SUM(s_score)) AS "排名"
FROM score
GROUP BY stu_id
ORDER BY total
  • 【22】:查询各科成绩前三名的学生信息与成绩
# 结果 
	第一名 课程1 成绩
	第二名 课程2 成绩
	第三名 课程3 成绩
	第一名 课程2 成绩...
SELECT a.score_rank, a.stu_id, b.s_name, a.cou_id, c.c_name, a.s_score
FROM (
	SELECT stu_id, cou_id, s_score, 
		row_number() over(PARTITION BY cou_id ORDER BY s_score DESC) AS score_rank 
	FROM score
) AS a
INNER JOIN student b
ON a.stu_id = b.s_id
INNER JOIN course c
ON a.cou_id = c.c_id
WHERE a.score_rank <= 3

score_rank  stu_id  s_name  cou_id  c_name  s_score  
----------  ------  ------  ------  ------  ---------
         1       1  赵雷           1  英语             98
         2       2  钱电           1  英语             92
         3       5  周梅           1  英语             84
         1       1  赵雷           2  语文             95
         2       8  王菊           2  语文             93
         3       5  周梅           2  语文             92
         1       2  钱电           3  数学             99
         2       1  赵雷           3  数学             97
         3       3  孙风           3  数学             92
         1       5  周梅           4  物理             97
         2       2  钱电           4  物理             91

# 结果 科目编号、科目名称、第一名成绩、第二名成绩、第三名成绩
SELECT a.cou_id, c.c_name, 
	MAX(CASE WHEN a.score_rank = 1 THEN b.s_name ELSE NULL END) AS "第一名同学", 
	MAX(CASE WHEN a.score_rank = 1 THEN a.s_score ELSE NULL END) AS "第一名成绩",
	MAX(CASE WHEN a.score_rank = 2 THEN b.s_name ELSE NULL END) AS "第二名同学", 
	MAX(CASE WHEN a.score_rank = 2 THEN a.s_score ELSE NULL END) AS "第二名成绩",
	MAX(CASE WHEN a.score_rank = 3 THEN b.s_name ELSE NULL END) AS "第三名同学", 
	MAX(CASE WHEN a.score_rank = 3 THEN a.s_score ELSE NULL END) AS "第三名成绩"
FROM (
	SELECT stu_id, cou_id, s_score, 
		row_number() over(PARTITION BY cou_id ORDER BY s_score DESC) AS score_rank 
	FROM score
) AS a
INNER JOIN student b
ON a.stu_id = b.s_id
INNER JOIN course c
ON a.cou_id = c.c_id
GROUP BY a.cou_id

cou_id  c_name  第一名同学  第一名成绩  第二名同学  第二名成绩  第三名同学  第三名成绩  
------  ------  ---------------  ---------------  ---------------  ---------------  ---------------  -----------------
     1  英语      赵雷                            98  钱电                            92  周梅                              84
     2  语文      赵雷                            95  王菊                            93  周梅                              92
     3  数学      钱电                            99  赵雷                            97  孙风                              92
     4  物理      周梅                            97  钱电                            91  (NULL)                      (NULL)
  • 【23】:统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[0-60]及所占百分比
# 注意这里 sum 和 count 在 case when else 后的区别
SELECT c.c_id, c.c_name,
	SUM(CASE WHEN sc.s_score <= 100 AND sc.s_score > 85 THEN 1 ELSE 0 END) "100-85",
	COUNT(CASE WHEN sc.s_score <= 100 AND sc.s_score > 85 THEN 1 ELSE NULL END) "85-70"
FROM score AS sc
INNER JOIN course AS c
ON sc.cou_id = c.c_id
GROUP BY c.c_id, c.c_name
  • 【24】:查询学生平均成绩及其名次
SELECT stu_id, st.s_name, AVG(s_score) avg_score, row_number() over (ORDER BY AVG(s_score) DESC) AS myrank
FROM score
INNER JOIN student st
ON st.s_id = stu_id
GROUP BY stu_id
  1. 查询每门课程的平均成绩,结果按平均成绩降序排列,平均成绩相同时,按课程编号升序排列
# 以课程为主体
SELECT sc.cou_id, c.c_name, AVG(sc.s_score) avg_score
FROM score sc
INNER JOIN course c
ON sc.cou_id = c.c_id
GROUP BY sc.cou_id
ORDER BY avg_score DESC, sc.cou_id ASC

cou_id  c_name  avg_score  
------  ------  -----------
     4  物理      94.0000    
     2  语文      79.3423    
     1  英语      79.1853    
     3  数学      79.1698    
     
# 一门课程有多个老师教,求每门课程不同老师教时的平均成绩
SELECT sc.cou_id, c.c_name, t.t_name, AVG(sc.s_score) avg_score
FROM score sc
INNER JOIN course c
ON sc.cou_id = c.c_id
INNER JOIN teacher t
ON c.t_id = t.t_id
GROUP BY sc.cou_id, t.t_id, t.t_name
ORDER BY avg_score DESC, sc.cou_id ASC
  • 【26】:查询每门课程被选修的学生数
SELECT cou_id, c_name, COUNT(s_score)
FROM score
INNER JOIN course
ON c_id = cou_id
GROUP BY cou_id
  • 【27】:查询出只有两门课程的全部学生的学号和姓名
SELECT s_id, s_name 
FROM student
WHERE s_id IN (
	SELECT stu_id
	FROM score
	GROUP BY stu_id HAVING COUNT(DISTINCT cou_id) = 2
)

SELECT st.s_id, st.s_name
FROM score sc
INNER JOIN student st
ON sc.stu_id = st.`s_id`
GROUP BY sc.stu_id HAVING COUNT(DISTINCT sc.cou_id) = 2
  • 【28】:查询男、女生人数
SELECT s_sex, COUNT(*) FROM student GROUP BY s_sex

SELECT
	SUM(CASE WHEN s_sex = "男" THEN 1 ELSE 0 END) AS "男生个数",
	SUM(CASE WHEN s_sex = "女" THEN 1 ELSE 0 END) AS "女生个数"
FROM student
  • 【29】:查询名字中含有"风"字的学生信息
# 重点:like 、 % 通配符
SELECT * FROM student WHERE s_name LIKE "%风%"
  • 【30】:查询同名同性学生名单,并统计同名人数
# 新建表stu
  s_id  s_name  s_sex   
------  ------  --------
     1  张三           
     2  张三           
     3  李四           
     4  王五           
     5  王五           
     6  刘六         
# 1.
SELECT a.s_name, a.s_sex, COUNT(*)
FROM stu a
GROUP BY a.s_name, a.s_sex  

s_name  s_sex   count(*)  
------  ------  ----------
张三                      2
李四                      1
王五                      1
王五                      1
刘六                      1     

# 2.
SELECT a.s_name, a.s_sex, COUNT(*)
FROM stu a
INNER JOIN stu b
ON a.s_id != b.s_id AND a.s_name = b.s_name AND a.s_sex = b.s_sex
GROUP BY a.s_name, a.s_sex

s_name  s_sex   count(*)  
------  ------  ----------
张三                      2
  • 【31】:查询1990年出生的学生名单
# 日期时间函数
SELECT * FROM student WHERE YEAR(s_age) = '1990'

# 日期格式:
YYYY-MM-DD
YYYYMMDD
YYYY/MM/DD
YYMMDD
SELECT MONTH('1990-02-20')

SELECT CURDATE()
  • 【32】:查询每门课程的平均成绩,结果按平均成绩降序排列,平均成绩相同时,按课程编号升序排列
SELECT cou_id, AVG(s_score) avg_score
FROM score
GROUP BY cou_id
ORDER BY avg_score ASC, cou_id DESC
  • 【33】:查询平均成绩大于等于85的所有学生的学号、姓名和平均成绩
SELECT b.s_id, b.s_name, AVG(a.s_score) AS avg_score
FROM score a
INNER JOIN student b
ON a.stu_id = b.s_id
GROUP BY b.s_id, b.s_name HAVING avg_score >= 85
  • 【34】:查询课程名称为"数学",且分数低于80的学生姓名和分数
SELECT a.stu_id, c.s_name, b.c_name, a.s_score
FROM score AS a
INNER JOIN course AS b
ON a.cou_id = b.c_id  
INNER JOIN student c
ON a.stu_id = c.s_id
WHERE b.c_name = "数学" AND a.s_score < 80
  • 【35】:查询所有学生的课程及分数情况
# 结果: 学生编号  学生姓名  课程1成绩  课程2成绩  课程3成绩, 无成绩时为null
SELECT a.s_id "学生编号", a.s_name "学生姓名", 
	MAX(CASE WHEN b.cou_id = 2 THEN b.s_score ELSE NULL END) AS "语文成绩", 
	MAX(CASE WHEN b.cou_id = 3 THEN b.s_score ELSE NULL END) AS "数学成绩", 
	MAX(CASE WHEN b.cou_id = 1 THEN b.s_score ELSE NULL END) AS "英语成绩"
FROM student a
LEFT JOIN score b
ON a.s_id = b.stu_id
INNER JOIN course c
ON b.cou_id = c.c_id
GROUP BY a.s_id, a.s_name

# 注意:如果不加max(),返回结果:
SELECT a.s_id "学生编号", a.s_name "学生姓名", 
	CASE WHEN b.cou_id = 2 THEN b.s_score ELSE NULL END AS "语文成绩", 
	CASE WHEN b.cou_id = 3 THEN b.s_score ELSE NULL END AS "数学成绩", 
	CASE WHEN b.cou_id = 1 THEN b.s_score ELSE NULL END AS "英语成绩"
学生编号  学生姓名  group by  case when == 语文  case when == 数学  case when == 英语
				    语文90       90                null             null
 1       张三        数学67      null				67			   null
					英语85       null			   null             85
由于group by分组,默认指挥返回每组第一条记录,比如case when == 语文时,即只会返回 90nullnull的结果。
那么如何返回成绩而不是null
max()函数:
	语文成绩 = max(90, null, null) = 90
	数学成绩 = max(null, 67, null) = 67
	英语成绩 = max(null, null, 85) = 85
  • 【36】:查询任何一门课程成绩在85分以上的姓名、课程名称和分数
SELECT c.s_id, c.s_name, b.c_name, a.s_score
FROM score a
INNER JOIN course b
ON a.cou_id = b.c_id
INNER JOIN student c
ON a.stu_id = c.s_id
WHERE a.s_score > 85
  • 【37】:查询不及格的课程
SELECT c.s_id, c.s_name, b.c_id, b.c_name, a.s_score
FROM score a
INNER JOIN course b
ON a.cou_id = b.c_id
INNER JOIN student c
ON a.stu_id = c.s_id
WHERE a.s_score < 60
ORDER BY b.c_id DESC
  • 【38】:查询课程编号为01且课程成绩在80分以上的学生的学号和姓名
SELECT c.s_id, c.s_name, b.c_id, b.c_name, a.s_score
FROM score a
INNER JOIN course b
ON a.cou_id = b.c_id
INNER JOIN student c
ON a.stu_id = c.s_id
WHERE a.s_score > 80 AND b.c_id = 3
  • 【39】:求每门课程的学生人数
SELECT cou_id, COUNT(*)
FROM score
GROUP BY cou_id
  • 【40】:查询选修"张三"老师所授课程的学生中,成绩最高的学生信息及其成绩
# 这样无法解决最高成绩有多个的情况
SELECT d.s_name, a.s_score
FROM score a
INNER JOIN course b
ON a.cou_id = b.c_id
INNER JOIN teacher c
ON c.t_id = b.t_id
INNER JOIN student d
ON a.stu_id = d.s_id
WHERE c.t_name = "张老师"
ORDER BY a.s_score DESC
LIMIT 0, 1

# 用max
SELECT d.s_name, a.s_score
FROM score a
INNER JOIN course b
ON a.cou_id = b.c_id
INNER JOIN teacher c
ON c.t_id = b.t_id
INNER JOIN student d
ON a.stu_id = d.s_id
WHERE c.t_name = "张老师" AND a.s_score = (SELECT MAX(s_score) FROM score)
  • 【41】:查询不同课程成绩相同的学生的学生编号、课程编号、学生成绩
# 理解:求所选课程成绩全部相同的学生信息(比如选修语文、英语,都是85分,只选修一门课程不考虑)
# 结果:学生编号、学生姓名、成绩(所选课程的成绩均一样)
SELECT a.stu_id, b.s_name, a.s_score
FROM score a
INNER JOIN student b
ON a.stu_id = b.s_id
GROUP BY a.stu_id, b.s_name, a.s_score 
HAVING MIN(a.s_score)=MAX(a.s_score) AND COUNT(*) > 1
  • 【42】:查询每门课程成绩最好的前两名(同22)
# 结果 
	第一名 课程1 成绩
	第二名 课程2 成绩
	第三名 课程3 成绩
	第一名 课程2 成绩...
SELECT a.score_rank, a.stu_id, b.s_name, a.cou_id, c.c_name, a.s_score
FROM (
	SELECT stu_id, cou_id, s_score, 
		row_number() over(PARTITION BY cou_id ORDER BY s_score DESC) AS score_rank 
	FROM score
) AS a
INNER JOIN student b
ON a.stu_id = b.s_id
INNER JOIN course c
ON a.cou_id = c.c_id
WHERE a.score_rank < 3


# 结果 科目编号、科目名称、第一名成绩、第二名成绩、第三名成绩
SELECT a.cou_id, c.c_name, 
	MAX(CASE WHEN a.score_rank = 1 THEN b.s_name ELSE NULL END) AS "第一名同学", 
	MAX(CASE WHEN a.score_rank = 1 THEN a.s_score ELSE NULL END) AS "第一名成绩",
	MAX(CASE WHEN a.score_rank = 2 THEN b.s_name ELSE NULL END) AS "第二名同学", 
	MAX(CASE WHEN a.score_rank = 2 THEN a.s_score ELSE NULL END) AS "第二名成绩"
FROM (
	SELECT stu_id, cou_id, s_score, 
		row_number() over(PARTITION BY cou_id ORDER BY s_score DESC) AS score_rank 
	FROM score
) AS a
INNER JOIN student b
ON a.stu_id = b.s_id
INNER JOIN course c
ON a.cou_id = c.c_id
GROUP BY a.cou_id
  • 【43】:统计每门课程的学生选修人数(超过5人的课程才统计)。要求输出课程号和选修人数,查询结果按人数降序排列,若人数相同,按课程号升序排列
SELECT a.cou_id, b.c_name, COUNT(DISTINCT a.stu_id) AS "人数"
FROM score a
INNER JOIN course b
ON a.cou_id = b.c_id
GROUP BY a.cou_id, b.c_name HAVING COUNT(DISTINCT a.stu_id) > 5
ORDER BY "人数" DESC, a.cou_id ASC
  • 【44】:检索至少选修两门课程的学生学号
SELECT a.stu_id, b.s_name 
FROM score a
INNER JOIN student b
ON a.stu_id = b.s_id
GROUP BY a.stu_id, b.s_name HAVING COUNT(a.cou_id) >= 2
  • 【45】:查询选修了全部课程的学生信息
SELECT a.stu_id, b.s_name 
FROM score a
INNER JOIN student b
ON a.stu_id = b.s_id
GROUP BY a.stu_id, b.s_name HAVING COUNT(a.cou_id) = (SELECT COUNT(c_id) FROM course)
  • 【46】:查询学生年龄
SELECT s_name, (YEAR(NOW()) - YEAR(s_age)) AS age FROM student

SELECT *, ROUND(DATEDIFF(CURDATE(), s_age) / 365) AS "虚岁", FLOOR(DATEDIFF(CURDATE(), s_age) / 365) AS "周岁"
FROM student
  • 【47】:查询过生日的学生
# 本周过生日的学生
select * from student where week(now()) = week(s_age)
# 下周过生日的学生
select * from student where week(now())+1 = week(s_age)
# 本月过生日的学生
select * from student where month(now()) = month(s_age)
# 下月过生日的学生
SELECT * FROM student WHERE MONTH(NOW())+1 = MONTH(s_age)

这就是微学网-程序员之家为你提供的"数据库——SQL语法练习"希望对你有所帮助.本文来自网络,转载请注明出处:http://www.weixuecn.cn/article/14364.html
网络编程 | 前端制作 | 数据库 | CMS教程 | 脚本编程 | 框架 | 服务器 | 微信开发 | APP开发 | 学习教程 |

凡本网站转载的文章、图片等资料的版权归版权所有人所有,因无法和版权所有者一一联系,如果本网站选取的文/图威胁到您的权益,请您及时和本网站联系。 我们会在第一时间内采取措施,避免给双方造 成不必要的损失。
© 2015-2021 微学网 版权所有,并保留所有权利。 备案号:粤ICP备09051474号-1

菜鸟学习网,提供各类程序编程入门,技巧