【问题标题】:How to join 3 tables and get the field with 2 different conditions?如何加入 3 个表并获得具有 2 个不同条件的字段?
【发布时间】:2019-08-12 21:48:38
【问题描述】:

我有 3 张桌子: 学生,课程(重要领域分数),StudentCourses(重要领域成绩)。

如果成绩大于或等于 70,则考试通过,因此学生将获得积分。 如果成绩低于 70,学生将不会获得积分。 如果学生的学分总和大于 10,则学生毕业。

我需要选择 StudentName、他的 PASSED 分数总和、他所有成绩的平均值。 我可以选择 StudentName、他的 PASSED 分数的总和和他的 PASSED 成绩的平均值。但我需要所有成绩的平均值。

我写了以下查询。

SELECT s.Name, SUM(c.CreditPoints) AS CreditPoints, AVG(sc.Grade) AS 
AverageGrade FROM Students s JOIN StudentCourse sc
ON s.Id = sc.StudentId
JOIN Courses c ON c.Id = sc.CourseIdenter code here
WHERE sc.Grade >= 70
GROUP BY s.Name
HAVING SUM(CreditPoints) > 10
ORDER BY CreditPoints

【问题讨论】:

  • 。 .用您正在使用的数据库标记您的问题。
  • 您能否向我们展示一下您刚刚编写的查询到底有哪些不适合的地方?您的预期输出是什么?

标签: sql sql-server


【解决方案1】:

虽然您只想选择学生的姓名,但请确保您也选择group by 学生的 ID(我相信 Students 表中有一列)因为 ethere 将是 2 个同名的学生。
你不能使用这个条件:

WHERE sc.Grade >= 70

因为这将删除您需要计算平均值的 Grade 所以信用点的总和将使用 CASE 语句计算:

select 
  s.Id, s.Name,
  sum(case when sc.grade >= 70 then c.creditpoints else 0 end) CreditPoints,
  avg(sc.grade) AverageGrade 
from students s 
inner join studentcourse sc on s.id = sc.studentid 
inner join courses c on c.id = sc.courseid
group by s.id, s.Name
having sum(case when sc.grade >= 70 then c.creditpoints else 0 end) > 10
order by CreditPoints desc;

由于您使用的是 SQL Server,因此您不能在 HAVING 子句中使用别名 CreditPoints,因此您必须重复 CASE 语句。

【讨论】:

  • 查看我编辑的有条款的答案。您在几分钟前标记了 sql server,我进行了编辑。
  • 谢谢!我收到了预期的结果。
【解决方案2】:

使用条件聚合:

SELECT s.Name,
       SUM(CASE WHEN sc.Grade >= 70 THEN c.CreditPoints ELSE 0 END) AS CreditPoints_passing,
       AVG(CASE sc.Grade >= 70 THEN sc.Grade END) AS AverageGrade_passing
       AVG(sc.Grade) AS AverageGrade
FROM Students s JOIN
     StudentCourse sc
     ON s.Id = sc.StudentId JOIN
     Courses c ON c.Id = sc.CourseIdenter code here
GROUP BY s.Name
HAVING CreditPoints_passing > 10  -- I think you want only 10 passing credits here
ORDER BY CreditPoints;

【讨论】:

    【解决方案3】:

    不确定您面临什么问题。对我来说,我能看到的唯一问题是 GROUP BY s.Name,因为多个学生可能具有相同的姓名,并且有可能从输入集中获得意外结果。您最好将 s.ID 用于 GROUP,如下所示-

    SELECT 
    ....
    GROUP BY s.Id  -- Change the grouping Key
    HAVING SUM(CreditPoints) > 10
    ORDER BY CreditPoints
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 2019-09-03
      • 2021-10-27
      相关资源
      最近更新 更多