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

关联三表展示产品及分类平均售价时SQL报错,求修正方案

问题分析与解决方案

你的报错原因很明确:Sales表(别名SS)里根本没有Category_ID字段,这个字段属于Products表,所以子查询里直接写SS.Category_ID = S.Category_ID肯定会找不到对应列。

我们需要先把Sales和Products关联起来,才能拿到每个销售记录对应的分类ID,进而计算分类级别的平均售价。下面给你两种可行的修正方案:

方案一:修正子查询,关联Products表

在子查询里把Sales表和Products表关联,获取每个销售记录对应的Category_ID,再进行聚合计算:

SELECT 
    s.Product_ID, 
    c.Category_Name AS Category,
    ROUND(
        (SELECT SUM(ss.Sales_Value) / SUM(ss.Sales_Quantity) 
         FROM Sales ss 
         JOIN Products pp ON ss.Product_ID = pp.Product_ID 
         WHERE pp.Category_ID = p.Category_ID),
        2
    ) AS average_sales_price_per_category
FROM Sales s 
JOIN Products p ON p.Product_ID = s.Product_ID 
JOIN Categories c ON c.Category_ID = p.Category_ID;

方案二:先预计算分类平均,再关联主查询(更高效)

先通过关联Sales和Products,一次性计算出每个分类的平均售价,再把这个结果和产品、分类表关联,这样只需要做一次聚合计算,性能更优:

WITH CategoryAvg AS (
    SELECT 
        p.Category_ID,
        ROUND(SUM(s.Sales_Value) / SUM(s.Sales_Quantity), 2) AS average_sales_price_per_category
    FROM Sales s
    JOIN Products p ON s.Product_ID = p.Product_ID
    GROUP BY p.Category_ID
)
SELECT 
    s.Product_ID,
    c.Category_Name AS Category,
    ca.average_sales_price_per_category
FROM Sales s
JOIN Products p ON s.Product_ID = p.Product_ID
JOIN Categories c ON p.Category_ID = c.Category_ID
JOIN CategoryAvg ca ON p.Category_ID = ca.Category_ID;

两种方案都能得到你期望的结果,我特意用ROUND()函数把结果保留两位小数,和你给出的示例输出格式完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 20:02:28