【问题标题】:Need SQL query to export students attendance report by classes需要SQL查询按班级导出学生出勤报告
【发布时间】:2021-12-05 03:22:41
【问题描述】:

我有 3 张桌子:

  • 学生桌
id name
1 Jhon
2 Emma
3 Oliver
  • 类表
id name
1 Math
2 Science
  • 考勤表
id student_id class_id
1 1 1
2 1 2
3 2 1

我尝试编写一个 SQL 查询来检索同时参加数学和科学课程的学生:

SELECT s.id, s.name
FROM attendance a
INNER JOIN students s ON a.student_id = s.id
WHERE a.class_id IN (1,2);

上面的代码结果是

id name
1 Jhon
2 Emma
1 Jhon

但艾玛只上数学课。

我知道这种行为是因为WHERE IN,它与WHERE a.class_id = 1 OR a.class_id = 2 相同。

但是我应该怎么做才能得到预期的结果,哪个是“Jhon”或只有 Jhon 的 ID,因为他是唯一一个参加数学和科学课程的人?

【问题讨论】:

  • 我建议使用聚合:COUNT、GROUP BY 和 HAVING,除了你已有的。

标签: sql


【解决方案1】:

要么参加两次,每节课一次:

SELECT s.id, s.name
FROM students s 
JOIN attendance a1 ON a1.student_id = s.id and a1.class_id = 1
JOIN attendance a2 ON a2.student_id = s.id and a2.class_id = 2

或同时加入两个班级并通过以下方式使用组:

SELECT s.id, s.name
FROM students s 
JOIN attendance a ON a.student_id = s.id and class_id in (1, 2)
GROUP BY s.id, s.name
HAVING COUNT(*) = 2

【讨论】:

    【解决方案2】:

    使用 CTE 会有所帮助,并且可以帮助您扩展到多个类。您还缺少 DISTINCT 关键字,这就是 Jhon 出现两次的原因。也许是这样的:

    WITH attendance_count(student_id, classes_attended)
    AS (
     SELECT
        student_id,
        COUNT(id) AS classes_attended
    
        FROM attendance a 
    
        -- change this to change the classes
        WHERE a.class_id IN (1,2)
    
        GROUP BY student_id
    )
    
    SELECT DISTINCT s.id, s.name
        FROM attendance_count 
        INNER JOIN students s ON attendance_count.student_id = s.id
    
        -- if different number of classes, change this
        WHERE classes_attended = 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多