3つのテーブルを結合する集計平均値を取得し、最初のテーブル内の各値の横にそれらを表示

Michi :

私はあなたにもで見つけることができる3つのテーブル持っているSQLのフィドルを

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


CREATE TABLE Products (
    Product_ID VARCHAR(255),
    Product_Name VARCHAR(255),
    Category_ID VARCHAR(255)
);
INSERT INTO Products
(Product_ID, Product_Name, Category_ID)
VALUES 
("P001", "Shirt", "C001"),
("P002", "Dress", "C001"),
("P003", "Hoodie", "C002"),
("P004", "Ball", "C002"),
("P005", "Ski", "C002"),
("P006", "Boot", "C003"),
("P007", "Flip-Flop", "C003");


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各製品のために。
2番目の表は、それぞれの詳細が含まれていますproduct
第三表には含まれてい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

私はからの溶液で行くことを試みた、この質問が、私は得ますError

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 Products p ON p.Product_ID = s.Product_ID
JOIN Categories c ON c.Category_ID = p.Category_ID;

エラー

Unknown column 'SS.Category_ID' in 'where clause'

私は期待どおりの結果を得るために、私のコードの変化には何が必要ですか?

scaisEdge:

あなたのテーブルには、回避するために、内部サブクエリで表示されていない状態内部サブクエリにあなたがグループ化されたaggreatedサブクエリに参加を使用することができます場所

SELECT
s.Product_ID,
Price_Category.average_sales_price_per_category
FROM Sales s
JOIN Products p ON p.Product_ID = s.Product_ID
JOIN
  (SELECT 
  c.Category_ID,
  c.Category_Name,
  SUM(s.Sales_Value) / SUM(s.Sales_Quantity) 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
  GROUP BY 1) Price_Category ON Price_Category.Category_ID = p.Category_ID;

SQLフィドル

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=15067&siteId=1