使用AdventureWorks2012查找每位客户的平均销售额

时间:2016-01-10 11:39:35

标签: sql sql-server tsql adventureworks

我正在使用MS AdventureWorks2012进行教程,我想使用AdventureWorks2012编写一个查询来查找每个客户的平均销售额(换句话说,每个客户的平均销售额)。以下是我的尝试,它没有运行。我在这里做错了什么?

SELECT  soh.CustomerID AS 'Customer ID'
,p.FirstName + ' ' + p.LastName AS 'Customer Name'
,AVG(soh.TotalDue) AS 'Average Sales Amount Per Customer'
FROM  Sales.SalesOrderHeader AS soh
INNER JOIN Sales.Customer AS c ON c.CustomerID = soh.CustomerID
INNER JOIN Person.BusinessEntityContact AS bec ON bec.PersonID = c.PersonID
INNER JOIN Person.Person AS p ON p.BusinessEntityID = bec.BusinessEntityID
GROUP BY p.FirstName , p.LastName, soh.CustomerID;

2 个答案:

答案 0 :(得分:1)

您的查询运行,它只返回一个空的结果集。

如果您查看BusinessEntityContact,则会将BusinessEntityID(一个客户业务)与PersonID相关联,SELECT soh.CustomerID AS 'Customer ID', p.FirstName + ' ' + p.LastName AS 'Customer Name', AVG(soh.TotalDue) AS 'Average Sales Amount Per Customer' FROM Sales.SalesOrderHeader AS soh INNER JOIN Sales.Customer AS c ON c.CustomerID = soh.CustomerID INNER JOIN Person.BusinessEntityContact AS bec ON bec.PersonID = c.PersonID INNER JOIN Person.Person AS p ON p.BusinessEntityID = bec.PersonID GROUP BY p.FirstName , p.LastName, soh.CustomerID; 是该业务的联系人。因此,如果您将查询更改为:

{{1}}

(注意第三个内连接) 你会得到635行。

答案 1 :(得分:-1)

在SQL单引号'识别一个字符串。如果您必须在结果列名称中包含空格,那么您可以使用双引号标识列名称"或者最好将列名包装在方括号中。

SELECT  
     soh.CustomerID AS [Customer ID]
    ,p.FirstName + ' ' + p.LastName AS [Customer Name]
    ,AVG(soh.TotalDue) AS [Average Sales Amount Per Customer]
FROM  Sales.SalesOrderHeader AS soh
   INNER JOIN Sales.Customer AS c ON c.CustomerID = soh.CustomerID
   INNER JOIN Person.BusinessEntityContact AS bec ON bec.PersonID = c.PersonID
   INNER JOIN Person.Person AS p ON p.BusinessEntityID = bec.BusinessEntityID
GROUP BY p.FirstName , p.LastName, soh.CustomerID;

否则你的语法对我来说没问题