Skip to content
Advertisement

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

Advertisement

Answer

 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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement