0

我正在学习使用 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;
4

2 回答 2

1

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

如果您查看BusinessEntityContact,它会将BusinessEntityID作为客户业务的 aPersonID与作为业务联系人的人相关联。因此,如果您将查询更改为:

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;

(注意第三个内部连接)您将获得 635 行。

于 2016-01-10T17:20:26.383 回答
-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;

否则你的语法对我来说看起来不错

于 2016-01-10T12:01:51.387 回答