SQL面试核心

SQL面试核心_第1张图片

group by里出现某个表的字段,select里面的列要么是该group by里出现的列,要么是带有聚合函数的列或者是别的表的列。

查询所有同学的学号、选课数、总成绩

select student_id,count(course_id),sum(score) from score group by student_id;

查询所有同学的学号、姓名、选课数、总成绩

select student_id,count(course_id),sum(score) from score s,student stu where s.student_id=stu.student_id group by s.student_id;

having

查询平均成绩大于60分的同学的学号和平均成绩

select student_id,avg(score) from score group by student_id having avg(score) > 60

查询没有学全所有课的同学的学号、姓名

select stu.student_id,stu.student_name from score s,student stu group by stu.student_id having count(s.course_id) < (select count(1) from course);

行转列

INSERT INTO student_scores(user_name,subject,score) VALUES ('张三', '语文', 80);
INSERT INTO student_scores(user_name,subject,score) VALUES ('张三', '数学', 90);
INSERT INTO student_scores(user_name,subject,score) VALUES ('张三', '英语', 70);
INSERT INTO student_scores(user_name,subject,score) VALUES ('张三', '生物', 85);
INSERT INTO student_scores(user_name,subject,score) VALUES ('李四', '语文', 80);
INSERT INTO student_scores(user_name,subject,score) VALUES ('李四', '数学', 92);
INSERT INTO student_scores(user_name,subject,score) VALUES ('李四', '英语', 76);
INSERT INTO student_scores(user_name,subject,score) VALUES ('李四', '生物', 88);
INSERT INTO student_scores(user_name,subject,score) VALUES ('码农', '语文', 60);
INSERT INTO student_scores(user_name,subject,score) VALUES ('码农', '数学', 82);
INSERT INTO student_scores(user_name,subject,score) VALUES ('码农', '英语', 96);
INSERT INTO student_scores(user_name,subject,score) VALUES ('码农', '生物', 78);

CREATE TABLE student_scores (
id int(11) NOT NULL AUTO_INCREMENT,
user_name varchar(255) DEFAULT NULL,
subject varchar(255) DEFAULT NULL,
score decimal(10,2) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

SELECT * from student_scores;

SELECT user_name,
MAX(IF (subject='语文',score,NULL)) '语文',
MAX(IF (subject='数学',score,NULL)) '数学',
MAX(IF (subject='英语',score,NULL))'英语',
MAX(IF (subject='生物',score,NULL))'生物'
FROM student_scores
GROUP BY user_name;

你可能感兴趣的:(SQL面试核心)