Ms Access 用一列减去并平均差异

Ms Access subtracting with a column and average the differences

tblStudent
studentid   sex
------------------
1           female
2           male

tblGrade
studentid   subject  Score
--------------------------
1           math     10
2           math     30
1           english  40
2           english  30
1           sci      20
2           sci      50

Access 查询循环如何计算男性和女性在数学和 sci 分数上的差异?

您可以对 subject 进行分组并使用 AVG 聚合函数计算平均值。

SELECT
    g.subject,
    AVG(IIf(s.sex='male', g.score, null)) AS avg_male,
    AVG(IIf(s.sex='female', g.score, null)) AS avg_female,
    AVG(IIf(s.sex='male', g.score, null)) -
    AVG(IIf(s.sex='female', g.score, null)) AS avg_diff
FROM
    tblStudent s
    INNER JOIN tblGrade g
        ON s.studentid = g.studentid
WHERE g.subject IN ('math', 'sci')
GROUP BY g.subject

请注意,Access 在平均计算中不包括 NULL 字段。因此,当性别不是我们需要的时,我们可以使用 NULL。