mysql - 获取加入第二张表的汇总平均值,并在第一张表中的每个值旁边显示它们

我有两个表,您也可以在SQL fiddle中找到它们:

CREATE TABLE Sales (
    Product_ID VARCHAR(255),
    Category_ID VARCHAR(255),
    Sales_Value VARCHAR(255),
    Sales_Quantity VARCHAR(255)
);
INSERT INTO Sales
(Product_ID, Category_ID, Sales_Value, Sales_Quantity)
VALUES 
("P001", "C001", "500", "200"),
("P002", "C001", "600", "100"),
("P003", "C002", "300", "250"),
("P004", "C002", "900", "400"),
("P005", "C002", "800", "600"),
("P006", "C003", "200", "150"),
("P007", "C003", "700", "550");


CREATE TABLE Categories (
    Category_ID VARCHAR(255),
    Category_Name VARCHAR(255)
);
INSERT INTO Categories
(Category_ID, Category_Name)
VALUES 
("C001", "Fashion"),
("C002", "Sport"),
("C003", "Shoes");


第一个表包含每个产品的 Sales
第二个表包含 Categories



现在,我要显示所有产品以及每个产品旁边的 average_sales_price_per_category。结果应如下所示:

Product_ID      Category      average_sales_price_per_category
P001             Fashion               3.66
P002             Fashion               3.66
P003             Sport                 1.60
P004             Sport                 1.60
P005             Sport                 1.60
P006             Shoes                 1.28
P007             Shoes                 1.28


我尝试使用 this question中的解决方案,但我认为 OVER子句在我的 MySQL版本中不可用:

SELECT 
s.Product_ID, 
c.Category_Name,
((SUM(s.Sales_Value * s.Sales_Quantity) over (partition BY c.Category_ID) /
SUM(s.Sales_Value) over (partition BY c.Category_ID)) as average_sales_price
FROM Sales s
JOIN Categories c ON c.Category_ID = s.Category_ID;


错误:


检查与您的MySQL服务器版本对应的手册以获取正确的语法,以在第4行的'over(partition BY c.Category_ID)/ SUM(s.Sales_Value)over(partition BY c.Cate')附近使用


我还能使用什么其他SQL来获得预期的结果?

最佳答案

对于旧版本,可以使用相关子查询:

SELECT s.Product_ID, c.Category_Name,
       (SELECT SUM(SS.Sales_Value) / SUM(SS.Sales_Quantity)
        FROM Sales SS 
        WHERE SS.Category_ID = S.Category_ID
       ) AS average_sales_price
FROM Sales s JOIN 
     Categories c 
     ON c.Category_ID = s.Category_ID;


这是 SQL Fiddle