-2

For each customer, determine the number of orders created in year 2007. If a customer has not created any order in year 2007, show 0 for that customer.

Show: customer ID, # of orders created in 2007 (show 0 if none)

Order by: customer ID

4

1 回答 1

0

OK - this is the third time I'm answering this type of question for you. It seems to me that by now you really should be able to take one of my answers and tweak & adapt it to yet another one of your question - don't you agree?

So here's the one to find the number of sales for each customer in 2007 - showing 0 for those customers who didn't have any sales.

-- determine the number of all sales in 2007 for each customer
;WITH SalesPerCustomer AS 
(
    SELECT 
        c.CustomerID,
        NumberOfSales = ISNULL(COUNT(soh.SalesOrderID), 0)
    FROM 
        Sales.Customer c 
    LEFT OUTER JOIN 
        Sales.SalesOrderHeader soh ON soh.CustomerID = c.CustomerID 
                                   AND soh.OrderDate >= '20070101' 
                                   AND soh.OrderDate < '20080101'
    GROUP BY    
        c.CustomerID    
)
SELECT 
    CustomerID ,
    NumberOfSales
FROM 
    SalesPerCustomer
ORDER BY 
    NumberOfSales DESC
于 2013-03-30T10:36:43.373 回答