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

CS50 SQL 2023第1题‘Dese’查询未通过检查,求问题原因

CS50 SQL 2023习题集1 'Dese'问题排查

问题场景

在完成CS50 SQL 2023习题集1的‘Dese’问题时,要求计算各学区生均支出的平均值,列名指定为Average District Per-Pupil Expenditure。编写的查询语句如下:

SELECT AVG(per_pupil_expenditure) AS "Average District Per-Pupil Expenditure" FROM expenditures;

但CS50检查提示结果不符,预期值与实际值数值看似一致却未通过。

问题根源

原查询的逻辑偏差在于:直接计算了expenditures表中所有per_pupil_expenditure记录的平均值,而题目要求的是先获取每个学区的生均支出,再计算这些学区值的平均值。

如果expenditures表中存在同一个学区的多条记录(比如按学年、子校区拆分的记录),原查询会把这些重复记录的生均支出全部纳入计算,导致最终结果和“各学区平均值”的要求不符。

修正后的查询

假设表中存在district_id字段用于唯一标识学区,正确的查询应该先按学区分组,确保每个学区只贡献一个生均支出值,再对这些值求平均:

SELECT AVG(district_per_pupil) AS "Average District Per-Pupil Expenditure"
FROM (
    -- 先获取每个学区的生均支出(若一个学区有多条记录,取该学区的平均)
    SELECT AVG(per_pupil_expenditure) AS district_per_pupil
    FROM expenditures
    GROUP BY district_id
) AS district_expenditures;

如果每个学区在expenditures表中仅有一条记录,也可以简化为:

SELECT AVG(per_pupil_expenditure) AS "Average District Per-Pupil Expenditure"
FROM (
    SELECT per_pupil_expenditure
    FROM expenditures
    GROUP BY district_id
) AS district_expenditures;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:30:57