我正在使用Adventure Works 2014数据库编写SQL查询。
我想向所有客户展示每个客户的订单数量。
我试图自己编写每个select语句(见下文),但我希望能够将两个查询合并为一个。
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
答案 0 :(得分:0)
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
答案 1 :(得分:0)
我添加了CONCAT,可能对您来说是新东西。无论如何,OVER(PARTITION BY column_name )子句被用作GROUP BY的替代,因为您打印的列比GROUP BY子句所允许的多。
答案 2 :(得分:0)
表Sales.Customer 参考: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