You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PieCloudDB中统计学生各科目考试次数(含0值)的SQL问题

统计每个学生各科目考试次数(含未参与科目0值)

我在PieCloudDB数据库中有三张表:Student表、Subject表和Exam表,需要统计每个学生参与各科目考试的次数,未参与的科目需输出0。但我写的SQL查询无法输出考试次数为0的记录:

SELECT student_id, subject_name, COUNT(*) AS test_count
FROM Examinations
GROUP BY student_id, subject_name
ORDER BY student_id, subject_name;

示例数据

Student表

student_idstudent_name
1Alice
2Bob
6Joe
13John

Subject表

subject_name
Math
Physics
Philosophy

Exam表(原查询中名为Examinations)

student_idsubject_name
1Math
1Physics
1Philosophy
2Philosophy
1Physics
1Math
13Math
13Philosophy
13Physics
2Math
1Math

期望输出

student_idstudent_namesubject_nametest_count
1AliceMath3
1AlicePhysics2
1AlicePhilosophy1
2BobMath1
2BobPhysics0
2BobPhilosophy1
6JoeMath0
6JoePhysics0
6JoePhilosophy0
13JohnMath1
13JohnPhysics1
13JohnPhilosophy1

解决方案

原查询只从Exam表取数据,自然无法包含没有考试记录的学生-科目组合。要解决这个问题,需要先生成所有学生和所有科目的笛卡尔积,再通过左连接关联Exam表,最后统计次数:

SELECT 
    s.student_id,
    s.student_name,
    sub.subject_name,
    COUNT(e.student_id) AS test_count
FROM Student s
CROSS JOIN Subject sub
LEFT JOIN Examinations e 
    ON s.student_id = e.student_id 
    AND sub.subject_name = e.subject_name
GROUP BY s.student_id, s.student_name, sub.subject_name
ORDER BY s.student_id, sub.subject_name;

关键说明:

  1. CROSS JOIN Subject:生成每个学生与所有科目的组合,确保即使没有考试记录的组合也会被包含。
  2. LEFT JOIN Examinations:保留所有学生-科目组合,匹配到的考试记录会被关联,未匹配的则为NULL。
  3. COUNT(e.student_id):只统计匹配到的考试记录数,未匹配的NULL会被忽略,结果为0(如果用COUNT(*)会把NULL行也算进去,得到错误的1)。

内容的提问来源于stack exchange,提问作者Meliodas Dragon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:10:07