AdventureWorks2012: For each customer, determine the number of orders created in year 2007. Show 0 for no order of that customer.

匆匆过客 提交于 2019-12-13 22:42:48

问题


AdventureWorks2012: Sql For each customer, determine the number of orders created in year 2007. If a customer has not created any order in year 2004, show 0 for that customer. Show: customer ID, # of orders created in 2007.


回答1:


Same approach as in my other response - use a CTE (Common Table Expression) to determine number of sales for each customer in the year 2007:

-- determine the number and total of all sales in 2007
;WITH SalesPerCustomer AS 
(
    SELECT 
        c.CustomerID,
        NumberOfSales = ISNULL(COUNT(soh.SalesOrderID), 0)
    FROM 
        Sales.Customer c 
    INNER 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

Ordered the output by number of sales descending, so you'll get the customer with the most sales first



来源:https://stackoverflow.com/questions/15702150/adventureworks2012-for-each-customer-determine-the-number-of-orders-created-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!