简体   繁体   中英

Adventure Works 2014 SQL Queries

I am writing a SQL query using Adventure Works 2014 database.

I want to show all customers and how many orders each customers have.

I tried to write each select statement by itself (see below), but I'd like to be able to combine both queries into one.

select  s.CustomerID ,p.FirstName +' '+p.LastName as Name 
from Sales.Customer s,Person.Person p 
where s.CustomerID=p.BusinessEntityID
order by s.CustomerID


select CustomerID ,count(SalesOrderID) as OrdersCount
from Sales.SalesOrderHeader
group by CustomerID
 SELECT s.CustomerID ,
        p.FirstName +' '+p.LastName as Name,
        count(SalesOrderID)
 FROM Sales.Customer s
 JOIN Person.Person p 
   ON s.CustomerID=p.BusinessEntityID
 LEFT JOIN Sales.SalesOrderHeader so
   ON s.Customer_ID = so.Customer_ID  
 GROUP BY s.CustomerID ,
        p.FirstName +' '+p.LastName as Name 
 order by s.CustomerID

单击此处查询其图像

I added CONCAT just as something new for u probably. Anyways the OVER(PARTITION BY column_name ) clause was used as a replacement for GROUP BY since you are printing more columns than what a GROUP BY clause would allow.

Table Sales.Customer References:Person.Person (PersonID -> BusinessEntityID)

SELECT s.CustomerID 
        ,p.FirstName +' '+p.LastName as Name
        ,COUNT(so.SalesOrderDetailID)
 FROM Sales.Customer s
 JOIN Person.Person p 
   ON s.PersonID=p.BusinessEntityID
 LEFT JOIN Sales.SalesOrderHeader h 
   ON h.CustomerID = s.CustomerID
 LEFT JOIN Sales.SalesOrderDetail so
   ON so.SalesOrderID = h.SalesOrderID
 GROUP BY s.CustomerID ,
        p.FirstName +' '+p.LastName
 order by s.CustomerID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM