My task is to write a query that will return sales information for each customer category and year. The columns required in the result set are:
- OrderYear - the year the orders were placed
- CustomerCategoryName - as it appears in the table
Sales.CustomerCategories
- CustomerCount - the number of unique customers placing orders for each
CustomerCategoryName
andOrderYear
- OrderCount - the number of orders placed for each
CustomerCategoryName
andOrderYear
- Sales - the subtotal from the orders placed, calculated from
Quantity
andUnitPrice
of the tableSales.OrderLines
- AverageSalesPerCustomer - the average sales per customer for each
CustomerCategoryName
andOrderYear
The results should be sorted in ascending order, first by order year, then by customer category name.
My attempt at a solution:
SELECT
CC.CustomerCategoryName,
YEAR(O.OrderDate) AS OrderYear,
COUNT(DISTINCT C.CustomerID) AS CustomerCount,
COUNT(DISTINCT O.OrderID) AS OrderCount,
SUM(OL.Quantity * OL.UnitPrice) AS Sales,
SUM(OL.Quantity * OL.UnitPrice) / COUNT(DISTINCT C.CustomerID) AS AverageSalesPerCustomer
FROM
Sales.CustomerCategories CC
INNER JOIN
Sales.Customers C ON C.CustomerCategoryID = CC.CustomerCategoryID
INNER JOIN
Sales.Orders O ON O.CustomerID = C.CustomerID
INNER JOIN
Sales.OrderLines OL ON OL.OrderID = O.OrderID
GROUP BY
CC.CustomerCategoryName, YEAR(O.OrderDate)
ORDER BY
YEAR(O.OrderDate), CC.CustomerCategoryName;
My OrderCount
seems correct. However, I don't believe my CustomerCount
is correct and my Sales
and AverageSalesPerCustomer
seem way off. The Categories
that do not have any customers and orders do not show up in my results.
Is the reason that my counts are off and that he categories that do not have any customers are omitted is because they only have null values? I believe the question is looking for all the categories.
I am using the sample tables of WideWorldImporters from Microsoft.
Any help would be appreciated as I am new to SQL and Joins are a very hard concept for me to understand.