083 Derived Tables

SQL

SELECT CategoryId,AVG(Price) as Price
INTO #tempCategoryPrice
FROM Products
GROUP BY CategoryId
SELECT
  p.Name as ProductName,
  c.Name as CategoryName,
t.Price as AvgPriceInCategory
FROM Products p
JOIN Categories c ON p.CategoryID=c.CategoryID
JOIN#tempCategoryPrice t ON c.CategoryId=t.CategoryId


SELECT
  p.Name as ProductName,
  c.Name as CategoryName,
t.Price as AvgPriceInCategory
FROM Products p
JOIN Categories c ON p.CategoryID=c.CategoryID
JOIN (SELECT CategoryId,AVG(Price) as Price
FROM Products
GROUP BY CategoryId) t ON c.CategoryId=t.CategoryId

猜你喜欢

转载自blog.csdn.net/KevinHuang2088/article/details/143416279