为什么 group by giving this not aggregated function 错误?
why is group by giving this not an aggregated function error?
我已经使用 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
目的是汇总按颜色分组的每种产品的标价,例如
它应该显示为
------+------------+--------
颜色 |标价 |姓名
------+------------+--------
红色 | 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.
如果我在没有内部联接的情况下执行此操作,即没有名称列
select p.Color, SUM(p.ListPrice) as total from SalesLT.Product p
group by p.Color
代码有效,但内部连接失败
为什么我看不出逻辑有问题,但还是会出现这个错误?我该如何解决这个问题?
谢谢
select p.Color, SUM(p.ListPrice) as total, pc.Name
group by p.Color
您需要将 pc.Name 添加到 GROUP BY 语句,因为 GROUP BY 必须包含 SELECT 子句中不属于聚合(如 SUM、COUNT 等)的所有列。
我已经使用 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
目的是汇总按颜色分组的每种产品的标价,例如
它应该显示为
------+------------+-------- 颜色 |标价 |姓名 ------+------------+-------- 红色 | 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.
如果我在没有内部联接的情况下执行此操作,即没有名称列
select p.Color, SUM(p.ListPrice) as total from SalesLT.Product p
group by p.Color
代码有效,但内部连接失败
为什么我看不出逻辑有问题,但还是会出现这个错误?我该如何解决这个问题?
谢谢
select p.Color, SUM(p.ListPrice) as total, pc.Name group by p.Color
您需要将 pc.Name 添加到 GROUP BY 语句,因为 GROUP BY 必须包含 SELECT 子句中不属于聚合(如 SUM、COUNT 等)的所有列。