13-复杂查询合集

image-20200812132737977

1. 行转列,列转行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
DROP TABLE IF EXISTS cangku;
CREATE TABLE `cangku` (
`PID` VARCHAR(10),
`PNUM` VARCHAR(10) NOT NULL,
`SID` VARCHAR(10) NOT NULL
)

INSERT INTO `cangku`
VALUES
('1', '10', '01'),
('1', '12', '02'),
('2', '8', '01'),
('3', '11', '01'),
('3', '8', '03');

-- 行转列,列转行
SELECT * FROM cangku;

SELECT `PID`,
MAX(CASE `SID` WHEN '01' THEN `PNUM` ELSE 0 END) AS 'SID01',
MAX(CASE `SID` WHEN '02' THEN `PNUM` ELSE 0 END) AS 'SID02',
MAX(CASE `SID` WHEN '03' THEN `PNUM` ELSE 0 END) AS 'SID03'
FROM `cangku`
GROUP BY `PID`;

1.1 行转列+统计

原数据:

image-20220209201612109

行转列+统计后:

image-20220209201628369

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
CREATE TABLE `userinfo` (
`id` int(11) NOT NULL COMMENT '主键',
`name` varchar(20) DEFAULT NULL COMMENT '姓名',
`sex` varchar(3) DEFAULT NULL COMMENT '性别',
`no` int(11) DEFAULT NULL COMMENT '编号',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='学生表';

INSERT INTO `userinfo` (`id`, `name`, `sex`, `no`)
VALUES ('1', '张三', '男', '1'),
('2', '李四', '男', '2'),
('3', '王五', '女', '1');

#方式1: CASE 列 WHEN 行 (需要临时表将统计字段计算出来)
SELECT `no` AS '编号',
sum(CASE sex WHEN '男' THEN `count` ELSE 0 END) AS '男生',
sum(CASE sex WHEN '女' THEN `count` ELSE 0 END) AS '女生'
FROM (SELECT `no`, sex, count(*) AS `count` FROM userinfo GROUP BY `no`, sex) tmp
GROUP BY `no`;

#方式2: 连表直接查询
SELECT `no` AS '编号',
(SELECT count(*) FROM userinfo u2 WHERE u1.`no`=u2.`no` AND u2.sex='男') AS '男生',
(SELECT count(*) FROM userinfo u2 WHERE u1.`no`=u2.`no` AND u2.sex='女') AS '女生'
FROM userinfo u1
GROUP BY `no`;

#方式1 与 方式2 在性能差异上并不大,暂无实测大量数据。

2. 保留最小ID删除重复值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 查询表中重复数据,删除重复数据,保留id最小的数据 #
DROP TABLE IF EXISTS team;

CREATE TABLE team (
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR (20)
) CHARSET = utf8;

INSERT INTO team (`name`)
VALUES ('a'), ('b'), ('b'), ('a'), ('c'), ('c');

-- 原始:
-- id name
-- 1 a
-- 2 b
-- 3 b
-- 4 a
-- 5 c
-- 6 c
-- 效果:
-- id name
-- 1 a
-- 2 b
-- 5 c

-- 查询显示重复的数据都是显示最前面的几条,因此不需要查询是否最小值
DELETE FROM team WHERE `name` IN(
SELECT `name` FROM (
SELECT `name` FROM team GROUP BY `name` HAVING COUNT(`name`) > 1
) e
) AND id NOT IN (
SELECT id FROM (
# 此处的 HAVING 可省略,添加有助于提升过滤数据效率 #
SELECT MIN(id) AS id FROM team GROUP BY `name` HAVING COUNT(`name`) > 1
) t
)

3. 过滤数据到新表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
DROP TABLE IF EXISTS `C`;

CREATE TABLE `C` (
`CID` VARCHAR (100) NOT NULL,
`Name` VARCHAR (50) DEFAULT NULL,
`Class` VARCHAR (20) DEFAULT NULL,
`Score` INT (11) DEFAULT NULL,
PRIMARY KEY (`CID`)
) ENGINE = INNODB DEFAULT CHARSET = utf8;

DROP TABLE IF EXISTS `Score`;

CREATE TABLE `Score` (
`Sid` INT (11) NOT NULL AUTO_INCREMENT,
`Class` VARCHAR (10) DEFAULT NULL,
`Score` INT (11) DEFAULT NULL,
PRIMARY KEY (`Sid`)
) ENGINE = INNODB AUTO_INCREMENT = 5 DEFAULT CHARSET = utf8;

/*Data for the table `Score` */
INSERT INTO `Score` (`Sid`, `Class`, `Score`)
VALUES
(1, '数学', 80),
(2, '计算机', 59),
(3, '计算机', 60),
(4, '数学', 55);

DROP TABLE IF EXISTS `Student`;

CREATE TABLE `Student` (
`Sid` INT (11) NOT NULL AUTO_INCREMENT,
`Name` VARCHAR (10) DEFAULT NULL,
`Age` INT (11) DEFAULT NULL,
PRIMARY KEY (`Sid`)
) ENGINE = INNODB AUTO_INCREMENT = 6 DEFAULT CHARSET = utf8;

/*Data for the table `Student` */
INSERT INTO `Student` (`Sid`, `Name`, `Age`)
VALUES
(1, '张三', 11),
(2, '赵四', 22),
(3, '张飞', 33),
(4, '李武', 22),
(5, NULL, 11);

-- 1.取出Name,Class,Score
SELECT `Name`, Class, Score FROM Student
LEFT JOIN Score ON Score.`Sid`=Student.`Sid`

-- 2.取出考试成绩不合格的学生
SELECT st.Sid, st.`Name`, sc.Score FROM Student AS st
LEFT JOIN Score AS sc ON sc.`Sid`=st.`Sid`
WHERE sc.`Score` < 60

-- 3.删除表A中没有考试成绩的学生记录
DELETE FROM Student WHERE Sid IN(
SELECT Sid FROM (
SELECT st.`Sid` FROM Student AS st
LEFT JOIN Score AS sc ON st.`Sid`=sc.`Sid`
WHERE sc.`Score` < 60
) AS s
)

-- 4.将表A 和 表B的不合格记录移至表C
INSERT INTO C (C.`CID`, `Name`, Class, Score)
SELECT REPLACE(UUID(), "-", "") AS Cid, `Name`, Class, Score FROM Student
LEFT JOIN Score ON Student.`Sid` = Score.`Sid`
WHERE Score.`Score` < 60

4. 连表查询 × 50

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
-- 建表
-- 学生表
DROP TABLE IF EXISTS Student;

CREATE TABLE `Student` (
`s_id` VARCHAR (20) NOT NULL COMMENT '学生id',
`s_name` VARCHAR (20) DEFAULT NULL COMMENT '学生姓名',
`s_birth` VARCHAR (20) DEFAULT NULL COMMENT '学生生日',
`s_sex` VARCHAR (10) DEFAULT NULL COMMENT '学生性别',
PRIMARY KEY (`s_id`)
);

-- 课程表
DROP TABLE IF EXISTS Course;

CREATE TABLE `Course` (
`c_id` VARCHAR (20) NOT NULL COMMENT '课程id',
`c_name` VARCHAR (20) DEFAULT NULL COMMENT '课程名称',
`t_id` VARCHAR (20) DEFAULT NULL COMMENT '老师id',
PRIMARY KEY (`c_id`)
);

-- 教师表
DROP TABLE IF EXISTS Teacher;

CREATE TABLE `Teacher` (
`t_id` VARCHAR (20) NOT NULL COMMENT '老师id',
`t_name` VARCHAR (20) DEFAULT NULL COMMENT '老师姓名',
PRIMARY KEY (`t_id`)
);

-- 成绩表
DROP TABLE IF EXISTS Score;

CREATE TABLE `Score` (
`s_id` VARCHAR (20) NOT NULL COMMENT '成绩id',
`c_id` VARCHAR (20) NOT NULL COMMENT '课程id',
`s_score` INT (3) DEFAULT NULL COMMENT '成绩分数',
PRIMARY KEY (`s_id`, `c_id`)
);

-- 插入学生表测试数据
insert into Student values('01' , '赵雷' , '1990-01-01' , '男');
insert into Student values('02' , '钱电' , '1990-12-21' , '男');
insert into Student values('03' , '孙风' , '1990-05-20' , '男');
insert into Student values('04' , '李云' , '1990-08-06' , '男');
insert into Student values('05' , '周梅' , '1991-12-01' , '女');
insert into Student values('06' , '吴兰' , '1992-03-01' , '女');
insert into Student values('07' , '郑竹' , '1989-07-01' , '女');
insert into Student values('08' , '王菊' , '1990-01-20' , '女');

-- 课程表测试数据
insert into Course values('01' , '语文' , '02');
insert into Course values('02' , '数学' , '01');
insert into Course values('03' , '英语' , '03');

-- 教师表测试数据
insert into Teacher values('01' , '张三');
insert into Teacher values('02' , '李四');
insert into Teacher values('03' , '王五');

-- 成绩表测试数据
insert into Score values('01' , '01' , 80);
insert into Score values('01' , '02' , 90);
insert into Score values('01' , '03' , 99);
insert into Score values('02' , '01' , 70);
insert into Score values('02' , '02' , 60);
insert into Score values('02' , '03' , 80);
insert into Score values('03' , '01' , 80);
insert into Score values('03' , '02' , 80);
insert into Score values('03' , '03' , 80);
insert into Score values('04' , '01' , 50);
insert into Score values('04' , '02' , 30);
insert into Score values('04' , '03' , 20);
insert into Score values('05' , '01' , 76);
insert into Score values('05' , '02' , 87);
insert into Score values('06' , '01' , 31);
insert into Score values('06' , '03' , 34);
insert into Score values('07' , '02' , 89);
insert into Score values('07' , '03' , 98);

image-20200813081042896

image-20200813081157306

image-20200813081250445

image-20200813081313660

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
-- 1.学生表
-- student(s_id,s_name,s_birth,s_sex) –学生编号,学生姓名, 出生年月,学生性别
-- 2.课程表
-- course(c_id,c_name,t_id) – –课程编号, 课程名称, 教师编号
-- 3.教师表
-- teacher(t_id,t_name) –教师编号,教师姓名
-- 4.成绩表
-- score(s_id,c_id,s_score) –学生编号,课程编号,分数

-- 1、查询"01"课程比"02"课程成绩高的学生的信息及课程分数
SELECT st.*, sc1.s_score, sc2.s_score, co.c_name FROM student AS st
INNER JOIN score AS sc1 ON st.s_id = sc1.s_id AND sc1.c_id = '01'
INNER JOIN score AS sc2 ON st.s_id = sc2.s_id AND sc2.c_id = '02'
INNER JOIN course AS co ON sc1.c_id = co.c_id
WHERE sc1.s_score > sc2.s_score;

-- 2、查询"01"课程比"02"课程成绩低的学生的信息及课程分数
SELECT st.*, sc1.s_score, sc2.s_score, co.c_name FROM student AS st
INNER JOIN score AS sc1 ON st.s_id = sc1.s_id AND sc1.c_id = '01'
INNER JOIN score AS sc2 ON st.s_id = sc2.s_id AND sc2.c_id = '02'
INNER JOIN course AS co ON sc1.c_id = co.c_id
WHERE sc1.s_score < sc2.s_score;

-- 3、查询平均成绩大于等于60分的同学的学生编号和学生姓名和平均成绩
SELECT st.s_id, st.s_name, AVG(sc.s_score) avgScore FROM student AS st
LEFT JOIN score AS sc ON sc.s_id = st.s_id
GROUP BY st.s_id
HAVING avgScore >= 60;

-- 4、查询平均成绩小于60分的同学的学生编号和学生姓名和平均成绩
-- (包括有成绩的和无成绩的)
SELECT st.s_id, st.s_name, AVG(sc.s_score) avgScore FROM student AS st
LEFT JOIN score AS sc ON sc.s_id = st.s_id
GROUP BY st.s_id HAVING avgScore < 60 OR avgScore IS NULL;

-- 5、查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩
SELECT st.s_id, st.s_name, COUNT(co.c_id) AS count, SUM(sc.s_score) AS sum FROM student AS st
LEFT JOIN score AS sc ON sc.s_id = st.s_id
LEFT JOIN course AS co ON co.c_id = sc.c_id
GROUP BY st.s_id;

-- 6、查询"李"姓老师的数量
SELECT COUNT(t.t_id) FROM teacher AS t
WHERE t.t_name LIKE '李%';

-- 7、查询学过"张三"老师授课的同学的信息
SELECT st.*, te.t_name FROM student AS st
LEFT JOIN score AS sc ON sc.s_id = st.s_id
LEFT JOIN course AS co ON co.c_id = sc.c_id
LEFT JOIN teacher AS te ON te.t_id = co.t_id
WHERE te.t_name = '张三';

-- 8、查询没学过"张三"老师授课的同学的信息
SELECT st.*, te.t_name FROM student AS st
LEFT JOIN score AS sc ON sc.s_id = st.s_id
LEFT JOIN course AS co ON co.c_id = sc.c_id
LEFT JOIN teacher AS te ON te.t_id = co.t_id
WHERE te.t_name != '张三';

-- 9、查询学过编号为"01"并且也学过编号为"02"的课程的同学的信息
SELECT st.*, sc.c_id FROM student AS st
LEFT JOIN score AS sc ON sc.s_id = st.s_id
WHERE sc.c_id IN ('01', '02');

-- 10、查询学过编号为"01"但是没有学过编号为"02"的课程的同学的信息
SELECT st.s_id, st.s_name, st.s_sex, st.s_birth, sc1.c_id FROM student AS st
LEFT JOIN (SELECT * FROM score WHERE c_id = '01') AS sc1 ON sc1.s_id = st.s_id
LEFT JOIN (SELECT * FROM score WHERE c_id = '02') AS sc2 ON sc2.s_id = st.s_id
WHERE sc1.c_id = '01'
AND sc2.c_id IS NULL;

-- 11、查询没有学全所有课程的同学的信息
SELECT st.*, COUNT(c_id) AS num FROM student AS st #分组统计每个学生的课程数,不等于总可成熟
LEFT JOIN score sc ON st.s_id = sc.s_id
GROUP BY sc.s_id
HAVING num != (SELECT COUNT(c_id) FROM course); #查询课程的总数

-- 12、查询至少有一门课与学号为"01"的同学所学相同的同学的信息
SELECT st.*, tmp.c_id FROM student AS st,
( #查询分数表中在01课程id内的学生id
SELECT DISTINCT sc.s_id, sc.c_id FROM score AS sc
WHERE c_id IN ( #学生01学过的课程id
SELECT c_id FROM score WHERE s_id = '01'
)
) AS tmp
WHERE st.s_id = tmp.s_id;

-- 13、查询和"01"号的同学学习的课程完全相同的其他同学的信息
SELECT st.* FROM student AS st
WHERE st.s_id IN ( #查询分数表里与01一样的分数个数的学生id(排除01)
SELECT s_id FROM score
WHERE s_id != '01'
AND c_id IN ( #查询01同学的课程id
SELECT c_id FROM score WHERE s_id = '01'
)
GROUP BY s_id
HAVING COUNT(*) = ( #查询01同学学过课程个数
SELECT COUNT(*) FROM score WHERE s_id = '01'
)
);

-- 14、查询没学过"张三"老师讲授的任一门课程的学生姓名
SELECT st.* FROM student AS st
WHERE st.s_id NOT IN ( #查询学过张三老师对应课程的学生id
SELECT sc.s_id FROM score AS sc
WHERE sc.c_id IN ( #查询张三老师教的课程id
SELECT co.c_id FROM course AS co, teacher AS te
WHERE co.t_id = te.t_id AND te.t_name = '张三'
)
);

-- 15、查询两门及其以上不及格课程的同学的学号,姓名及其平均成绩
SELECT st.s_id, st.s_name, count(*) failCount, avg(sc.s_score) avg FROM score sc
LEFT JOIN student st ON sc.s_id = st.s_id
WHERE sc.s_score < 60 #先查不及格的数量>2的学生id
GROUP BY sc.s_id HAVING failCount >= 2;

-- 16、检索"01"课程分数小于60,按分数降序排列的学生信息
SELECT st.*, sc.s_score FROM score sc
LEFT JOIN student st ON sc.s_id = st.s_id
WHERE sc.c_id = '01' AND sc.s_score < 60
ORDER BY sc.s_score DESC;

-- 17、按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩
SELECT st.*, sc.s_score, t.avg FROM student st
LEFT JOIN score sc ON sc.s_id = st.s_id
LEFT JOIN (SELECT s_id, avg(s_score) avg FROM score GROUP BY s_id) t ON t.s_id = st.s_id
ORDER BY avg DESC;

-- 18.查询各科成绩最高分、最低分和平均分:以如下形式显示:课程ID,课程name,最高分,最低分,平均分,及格率,中等率,优良率,优秀率
-- 及格为>=60,中等为:70-80,优良为:80-90,优秀为:>=90
SELECT c.c_id, c.c_name, MAX(sc.s_score) "最高分", MIN(sc.s_score) "最低分", AVG(sc.s_score) "平均分"
,((SELECT COUNT(s_id) FROM score WHERE s_score>=60 AND c_id=c.c_id )/(SELECT COUNT(s_id) FROM score WHERE c_id=c.c_id)) "及格率"
,((SELECT COUNT(s_id) FROM score WHERE s_score>=70 AND s_score<80 AND c_id=c.c_id )/(SELECT COUNT(s_id) FROM score WHERE c_id=c.c_id)) "中等率"
,((SELECT COUNT(s_id) FROM score WHERE s_score>=80 AND s_score<90 AND c_id=c.c_id )/(SELECT COUNT(s_id) FROM score WHERE c_id=c.c_id)) "优良率"
,((SELECT COUNT(s_id) FROM score WHERE s_score>=90 AND c_id=c.c_id )/(SELECT COUNT(s_id) FROM score WHERE c_id=c.c_id)) "优秀率"
FROM course c
LEFT JOIN score sc ON sc.c_id=c.c_id
GROUP BY c.c_id;

-- 19、按各科成绩进行排序,并显示排名
SET @rank = 0;
SELECT sc.*, @rank := @rank + 1 AS r FROM score sc
ORDER BY sc.s_score;

-- 20、查询学生的总成绩并进行排名
SET @rank = 0;
SELECT a.*, @rank := @rank + 1 AS r
FROM (SELECT sc.*, sum(sc.s_score) scoreSum FROM score sc
GROUP BY s_id
ORDER BY scoreSum DESC) AS a;

-- 21、查询不同老师所教不同课程平均分从高到低显示


-- 22、查询所有课程的成绩第2名到第3名的学生信息及该课程成绩


-- 23、统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[0-60]及所占百分比


-- 24、查询学生平均成绩及其名次


-- 25、查询各科成绩前三名的记录


-- 26、查询每门课程被选修的学生数


-- 27、查询出只有两门课程的全部学生的学号和姓名


-- 28、查询男生、女生人数


-- 29、查询名字中含有"风"字的学生信息


-- 30、查询同名同性学生名单,并统计同名人数


-- 31、查询1990年出生的学生名单


-- 32、查询每门课程的平均成绩,结果按平均成绩降序排列,平均成绩相同时,按课程编号升序排列


-- 33、查询平均成绩大于等于85的所有学生的学号、姓名和平均成绩


-- 34、查询课程名称为"数学",且分数低于60的学生姓名和分数


-- 35、查询所有学生的课程及分数情况;


-- 36、查询任何一门课程成绩在70分以上的姓名、课程名称和分数


-- 37、查询不及格的课程


-- 38、查询课程编号为01且课程成绩在80分以上的学生的学号和姓名


-- 39、求每门课程的学生人数


-- 40、查询选修"张三"老师所授课程的学生中,成绩最高的学生信息及其成绩


-- 41、查询不同课程成绩相同的学生的学生编号、课程编号、学生成绩


-- 42、查询每门功成绩最好的前两名


-- 43、统计每门课程的学生选修人数(超过5人的课程才统计)。要求输出课程号和选修人数,查询结果按人数降序排列,若人数相同,按课程号升序排列


-- 44、检索至少选修两门课程的学生学号


-- 45、查询选修了全部课程的学生信息


-- 46、查询各学生的年龄


-- 47、查询本周过生日的学生
-- 此处可能有问题,week函数取的为当前年的第几周,2017-12-12是第50周而2018-12-12是第49周,可以取月份,day,星期几(%w),
-- 再判断本周是否会持续到下一个月进行判断,太麻烦,不会写


-- 48、查询下周过生日的学生


-- 49、查询本月过生日的学生

-- 50、查询下月过生日的学生
-- 注意:当 当前月为12时,用month(now())+1为13而不是1,可用timestampadd()函数或mod取模


13-复杂查询合集
https://janycode.github.io/2017/06/18/05_数据库/01_MySQL/13-复杂查询合集/
作者
Jerry(姜源)
发布于
2017年6月18日
许可协议