数据分析 | MySQL45道练习题(37~45)

【题目总览】

# 37统计每门课程的学生选修人数(超过5人的课程才统计)

# 38检索至少选修两门课程的学生学号 

# 39查询选修了全部课程的学生信息 

# 40查询各个学生的年龄,只按年份来算 

# 41按照出生日期来算,当前月日 < 出生年月的月日 则年龄减一 

# 42查询本周过生日的学生 

# 43查询下周过生日的学生 

# 44查询本月过生日的学生 

# 45查询下月过生日的学生 

37.统计每门课程的学生选修人数(超过5人的课程才统计)
-- 【分析】分组统计 

# 法一
SELECT cid,COUNT(sid) 选修人数
FROM sc 
GROUP BY cid
HAVING COUNT(sid) > 5;

# 法二
SELECT cid,COUNT(1) 选修人数
FROM sc 
GROUP BY cid
HAVING COUNT(1) > 5;

-- 知识点补充 --
# COUNT(1) COUNT(*) COUNT(列名)的区别
# COUNT(1)包含忽略所有列,用1代表代码行,统计时不会忽略列值为NULL
# COUNT(*)包含所有列,相当于行数,统计时,不会忽略列值为NULL
# COUNT(列名)只包含列名那一列,统计时忽略列为NULL(某字段为NULL,不计数)

# 38检索至少选修两门课程的学生学号 

SELECT sid 学号,COUNT(cid) 选修课程数
FROM sc
GROUP BY sid
HAVING COUNT(1) >= 2;

# 39查询选修了全部课程的学生信息 

SELECT s.*
FROM sc
INNER JOIN student s
ON sc.sid = s.sid
GROUP BY sid
HAVING COUNT(1) = (SELECT COUNT(1) FROM course);

SELECT s.*
FROM sc
INNER JOIN student s
ON sc.sid = s.sid
GROUP BY sid
HAVING COUNT(sc.cid) = (SELECT COUNT(cid) FROM course);

# 40查询各个学生的年龄,只按年份来算 

-- 【分析】使用日期函数进行相减 --
SELECT *,YEAR(CURDATE())-YEAR(sage) 年龄
FROM student;

SELECT *,YEAR(NOW())-YEAR(sage) 年龄
FROM student;

# 41按照出生日期来算,当前月日 < 出生年月的月日 则年龄减一 

-- 【分析】日期相减函数timestampdiff(year,参数1,参数2) --
SELECT *,
	  TIMESTAMPDIFF(YEAR,sage,NOW()) age
FROM student;

# 42查询本周过生日的学生 

-- 【分析】使用week()函数
SELECT *,
       WEEK(sage),
       WEEK(NOW())
FROM student
WHERE WEEK(sage)=WEEK(NOW());

# 43查询下周过生日的学生 

SELECT *,
       WEEK(sage),
       WEEK(NOW())
FROM student
WHERE WEEK(sage)=WEEK(NOW())+1;

# 44查询本月过生日的学生 

-- 【分析】使用month()函数 --
SELECT *,
       MONTH(sage),
       MONTH(NOW())
FROM student
WHERE MONTH(sage)=MONTH(NOW());

# 45查询下月过生日的学生 

SELECT *,
       MONTH(sage),
       MONTH(NOW())
FROM student
WHERE MONTH(sage)=MONTH(NOW())+1;

你可能感兴趣的:(MySQL,数据分析,数据挖掘,sql)