SQL INNER JOIN - 连接中的列名也在 select *错误*

SQL INNER JOIN - Column name in join is also in select *error*

我对 SQL 还是很陌生,遇到了一些问题。我使用的是经典 Northwind 数据库的变体。我正在使用 Microsoft SQL Server Management Studio。

问题是:

/*
Join Products and ProductVendors to display by product, the product
number, the average wholesale price, and the average retail price.
*/

这是我得到的:

SELECT Products.productNumber As [Product Number],
       CAST(AVG(wholesalePrice) as decimal (8,2)) As [Average Wholesale Price],
       CAST(AVG(retailPrice) as decimal (8,2))  As [Average Retail Price]
FROM Products INNER JOIN ProductVendors 
       ON Products.productNumber = ProductVendors.productNumber

这是我得到的错误:

Msg 8120, Level 16, State 1, Line 2
Column 'Products.productNumber' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

异常文本不言自明。由于您使用的是聚合函数(在您的情况下为 avg),因此您也必须按 Products.productNumber 进行分组。

select Products.productNumber aa [Product Number],
       CAST(AVG(wholesalePrice) as decimal (8,2)) as [Average Wholesale Price],
       CAST(AVG(retailPrice) as decimal (8,2))  as [Average Retail Price]
from Products inner join ProductVendors 
    on Products.productNumber = ProductVendors.productNumber
group by Products.productNumber

如果要使用聚合函数,必须有group by语句。

SELECT Products.productNumber As [Product Number],
       CAST(AVG(wholesalePrice) as decimal (8,2)) As [Average Wholesale Price],
       CAST(AVG(retailPrice) as decimal (8,2))  As [Average Retail Price]
FROM Products INNER JOIN ProductVendors ON Products.productNumber = ProductVendors.productNumber
group by Products.productNumber 

group by 语句必须包含所有不在聚合函数中的列

如果您使用 AGGREGATE 函数,则必须指定 GROUP BY 子句。

SELECT Products.productNumber As [Product Number],
       CAST(AVG(wholesalePrice) as decimal (8,2)) As [Average Wholesale Price],
       CAST(AVG(retailPrice) as decimal (8,2))  As [Average Retail Price]
FROM Products 
INNER JOIN ProductVendors ON Products.productNumber = ProductVendors.productNumber
GROUP BY Products.productNumber 

如果您使用 AGGREGATE 函数,则必须指定 GROUP BY 子句,此处您选择 ProductNumber 因此在

上指定 GROUP BY 子句
SELECT Products.productNumber As [Product Number],
       CAST(AVG(wholesalePrice) as decimal (8,2)) As [Average Wholesale Price],
       CAST(AVG(retailPrice) as decimal (8,2))  As [Average Retail Price]
FROM Products 
INNER JOIN ProductVendors ON Products.productNumber = ProductVendors.productNumber
GROUP BY Products.productNumber