Skip to content

Instantly share code, notes, and snippets.

@marti1125
Created July 30, 2014 01:04
Show Gist options
  • Save marti1125/258995cd2f35bcedd74d to your computer and use it in GitHub Desktop.
Save marti1125/258995cd2f35bcedd74d to your computer and use it in GitHub Desktop.
db 1
WITH ec AS ( SELECT C.LastName AS Customer
, e.LastName AS SalesPerson
, s.ProductID
, p.Name AS ProductName
, SUM(s.Quantity) AS quantity
, SUM(p.Price * s.Quantity) AS amount
, SUM(SUM(s.Quantity)) OVER (PARTITION BY s.ProductID)*1.0/SUM(COUNT(*)) OVER (PARTITION BY s.ProductID) AS Avg_Qty
FROM dbo.Sales s
JOIN dbo.Customers c ON s.CustomerID = c.CustomerID
JOIN dbo.Employees e ON s.SalesPersonID = e.EmployeeID
JOIN dbo.Products p ON s.ProductID = p.ProductID
WHERE p.Name LIKE 'Paint%'
GROUP BY C.LastName
, e.LastName
, s.ProductID
, p.Name
)
SELECT *
FROM ec
WHERE quantity < Avg_Qty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment