2015-04-29 40 views
0

我對SQL仍然很陌生,遇到問題。我正在使用經典Northwind數據庫的變體。我正在使用Microsoft SQL Server Management Studio。SQL INNER JOIN - 連接中的列名也在選擇*錯誤*

這裏的問題是:

/* 
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 

這是我得到的錯誤:

消息8120 ,等級16,狀態1,行2
列'Products.productNumber'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。

+0

GROUP BY條款是MySQL或MS SQL服務器? – Alex

+0

使用:.... group by Products.productNumber,wholesale價格,retailPrice – apomene

+0

絕對不是mysql - 它無法關心如果所有的選擇字段都在'group by' –

回答

4

異常文本是不言自明的。既然你正在使用聚合函數(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 
1

如果要使用聚合函數,則必須具有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聲明必須包含所有列至極不是一個聚合函數

0

如果使用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 
0

如果使用AGGREGATE功能則GROUP BY條款,必須在這裏指定您選擇ProductNumber使指定對

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