2015-03-02 33 views
-1

我已經使用AdventureworksLT2008R2此查詢,該查詢是爲什麼組通過給這不是一個聚合函數錯誤?

select p.Color, SUM(p.ListPrice) as total, pc.Name from SalesLT.Product p 
inner join SalesLT.ProductCategory pc on p.ProductCategoryID=pc.ProductCategoryID 
group by p.Color 
go 

目的是通過sumup顏色例如分組的每個產品的定價

它應該顯示像

------ + ----------- --------- +顏色 | ListPrice |名稱 ------ + ----------- + --------- red | 100000 |自行車 黑色| 12000 |服裝 ------------------------------

,而是它給這個錯誤

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

如果我這樣做thsi沒有內部聯接,即沒有名稱列

select p.Color, SUM(p.ListPrice) as total from SalesLT.Product p 
group by p.Color 

代碼的作品,但它未能與內加入

爲什麼即使出現這種錯誤我看到什麼錯什麼邏輯?我該如何解決這個問題?

感謝

+0

因爲它不是......的組成部分,而且......與錯誤消息完全一樣狀態。 – 2015-03-02 15:37:23

+0

...它不是按列列表分組的一部分,也不是在聚合表達式內。 – 2015-03-02 15:38:13

+0

我應該從組中刪除顏色並添加ListPrice,但不能按顏色顯示 – AndrewMC 2015-03-02 15:39:41

回答

2

選擇p.Color,SUM(p.ListPrice)爲總,pc.Name 組由p.Color

您需要pc.Name添加到GROUP BY語句,因爲GROUP BY必須具有SELECT子句中不屬於SUM,COUNT等聚合的所有列。

相關問題