Advertisement
StoyanGrigorov

20. Products by One Distributor

Feb 19th, 2017
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.17 KB | None | 0 0
  1. --20. Products by One Distributor
  2.  
  3. WITH Res_CTE (ProductName, DistributorName)
  4. AS
  5. (
  6.     SELECT
  7.                     p.Name AS [ProductName],
  8.                     d.Name AS [DistributorName]
  9.                 FROM Products AS p
  10.                 INNER JOIN Feedbacks AS f
  11.                 ON f.ProductId = p.Id
  12.                 INNER JOIN ProductsIngredients AS pin
  13.                 ON pin.ProductId = p.Id
  14.                 INNER JOIN Ingredients AS i
  15.                 ON i.Id = pin.IngredientId
  16.                 INNER JOIN Distributors AS d
  17.                 ON d.Id = i.DistributorId
  18.                 INNER JOIN Countries AS c
  19.                 ON c.Id = d.CountryId
  20.                 GROUP BY p.Id, p.Name, d.Name, c.Name
  21. )
  22.  
  23. SELECT
  24.     p.Name AS [ProductName],
  25.     AVG(f.Rate) AS [ProductAverageRate],
  26.     d.Name AS [DistributorName],
  27.     c.Name AS [DistributorCountry]
  28. FROM Products AS p
  29. INNER JOIN Feedbacks AS f
  30. ON f.ProductId = p.Id
  31. INNER JOIN ProductsIngredients AS pin
  32. ON pin.ProductId = p.Id
  33. INNER JOIN Ingredients AS i
  34. ON i.Id = pin.IngredientId
  35. INNER JOIN Distributors AS d
  36. ON d.Id = i.DistributorId
  37. INNER JOIN Countries AS c
  38. ON c.Id = d.CountryId
  39. GROUP BY p.Id, p.Name, d.Name, c.Name
  40. HAVING p.Name IN
  41.                 (
  42.                     SELECT r.ProductName
  43.                     FROM Res_CTE AS r
  44.                     GROUP BY r.ProductName
  45.                     HAVING COUNT(r.DistributorName) = 1
  46.                 )
  47. ORDER BY p.Id
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement