Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...