写一些简单的SQL

这是一个关于学生,成绩以及课程的三表相关联查,下面是我的表的详细信息:

名字不好听大家可以随便改.....

成绩表:

课程表:

学生表:

接下来就是咱们的sql条件查询了:

-- 1、用一条 SQL 语句查询 学生表每门课都大于 80 分的学生姓名。(禁用not in)

SELECT TS.stuname FROM t_student ts LEFT JOIN t_chengji tc ON ts.id=tc.stuid LEFT JOIN t_kecheng tk on tc.kechengid=tk.kechengid GROUP BY TS.stuname  HAVING MIN(TC.chengji)>80

-- 2、查询各科成绩前两名的记录
SELECT 
    tc.chengji,
    tc.id,
    tc.kechengid,
    tc.stuid
FROM 
    t_chengji tc 
    LEFT JOIN t_chengji tc1 ON tc.id=tc1.id
    AND tc.chengji <= tc1.chengji
GROUP BY
    tc.chengji,
    tc.id,
    tc.kechengid,
    tc.stuid
HAVING
    COUNT(tc1.kechengid)<=2
ORDER BY
    tc.kechengid,
    tc.chengji DESC
    
-- 3.按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩
SELECT ts.id,TS.stuname,tc1.chengji 语文,tc2.chengji 数学,tc3.chengji 英语,平均值
FROM t_student ts
LEFT JOIN t_chengji tc1 
ON ts.id=tc1.stuid  and tc1.kechengid=1
LEFT JOIN t_chengji tc2
ON ts.id=tc2.stuid  and tc2.kechengid=2
LEFT JOIN t_chengji tc3
ON ts.id=tc3.stuid  and tc3.kechengid=3
LEFT JOIN (SELECT ts.id,avg(tc.chengji) as 平均值
FROM t_student ts 
LEFT JOIN t_chengji tc
ON ts.id=tc.stuid
GROUP BY ts.id ) H
ON ts.id=H.id
ORDER BY 平均值 DESC

-- 4、查询没学过”语文”课程的学生姓名 禁用not in
SELECT ts.stuname 
FROM t_student ts
WHERE NOT EXISTS(
    SELECT tc.kechengid FROM t_chengji tc
    WHERE tc.kechengid=1
    and ts.id=tc.stuid
    )

-- 5、查询两门及其以上不及格课程的同学的学号,姓名及其平均成绩
SELECT ts.id,ts.stuname,b.avg_chengji FROM t_student ts
JOIN (SELECT tc.stuid,AVG(tc.chengji)as avg_chengji FROM t_chengji tc GROUP BY tc.stuid)b ON ts.id=b.stuid
where ts.id IN
    (SELECT tc.stuid FROM t_chengji tc WHERE tc.chengji<60 GROUP BY tc.stuid HAVING COUNT(tc.stuid)>=2)


-- 6、查询不同课程平均分从高到低显示
SELECT AVG(tc.chengji) 语文,AVG(tc1.chengji) 数学,AVG(tc2.chengji) 英语 FROM t_kecheng tk
LEFT JOIN t_chengji tc 
ON tc.kechengid=tk.kechengid AND tk.kechengid=1
LEFT JOIN t_chengji tc1
ON tc1.kechengid=tk.kechengid AND tk.kechengid=2
LEFT JOIN t_chengji tc2
ON tc2.kechengid=tk.kechengid AND tk.kechengid=3
ORDER BY  AVG(tc.chengji),AVG(tc1.chengji),AVG(tc2.chengji)DESC 


-- 实现行转列
SELECT tc.stuid, 
SUM(IF(tc.kechengid=1,tc.chengji,0)) as '语文', 
SUM(IF(tc.kechengid=2,tc.chengji,0)) as '数学', 
SUM(IF(tc.kechengid=3,tc.chengji,0)) as '英语'
FROM t_chengji tc 
GROUP BY tc.stuid
ORDER BY tc.chengji DESC

热爱生活,热爱代码!

猜你喜欢

转载自blog.csdn.net/m0_67864787/article/details/127657660