3

使用聚合函数时,我在理解 Group By 时遇到问题。我在不使用内部连接的情况下理解它很好,但现在我不明白要分组的内容。

这是我的代码。

SELECT  ProductName,
        Products.ProductNumber,
        AVG(WholesalePrice),
        AVG(RetailPrice)


FROM    Products INNER JOIN ProductVendors
        ON Products.ProductNumber = ProductVendors.DaysToDeliver;

如您所知,我正在尝试查找平均价格,但我不知道按什么分组。我尝试按那里的所有内容进行分组,但没有一个会起作用。有什么建议么?

以下是错误:选择列表中的“Products.ProductName”列无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

4

1 回答 1

1

基本上,对于任何 DBMS GROUP BY,您都需要未在其上执行聚合函数的项目:

SELECT Products.ProductName AS ProductName
    ,Products.ProductNumber AS ProductNumber
    ,AVG(Products.WholesalePrice) AS AvgWholesalePrice
    ,AVG(Products.RetailPrice) AS AvgRetailPrice
FROM Products Products
INNER JOIN ProductVendors Vendors ON Products.ProductNumber = Vendors.DaysToDeliver    
GROUP BY Products.ProductName, Products.ProductNumber;

此外,在执行JOINs 时,您应该真正适当地为表设置别名,然后使用它们的字段引用别名。它更透明,对 SQL 优化器的隐式翻译要求更少,并且允许更好的维护。

于 2013-11-18T21:19:40.563 回答