我对 Northwind 数据库 Products Table
运行了一个查询,如下所示
select * from Northwind.dbo.Products GROUP BY CategoryID
并且遇到了错误。我相信您也会遇到同样的错误。那么我需要执行的正确语句是什么来根据类别 ID 对所有产品进行分组。
编辑:这确实有助于理解很多
http://weblogs.sqlteam.com/jeffs/archive/2007/07/20/but-why-must-that-column-be-contained-in-an-aggregate.aspx
I ran a query against Northwind database Products Table
like below
select * from Northwind.dbo.Products GROUP BY CategoryID
and i was hit with a error. I am sure you will also be hit by same error. So what is the correct statement that i need to execute to group all products with respect to their category id's.
edit: this like really helped understand a lot
http://weblogs.sqlteam.com/jeffs/archive/2007/07/20/but-why-must-that-column-be-contained-in-an-aggregate.aspx
发布评论
评论(2)
您需要使用聚合函数,然后按任何非聚合列进行分组。
我建议阅读GROUP BY。
You need to use an Aggregate function and then group by any non-aggregated columns.
I recommend reading up on GROUP BY.
如果您在查询中使用
GROUP BY
,则SELECT
语句中的所有项目都必须包含在聚合函数中,例如Sum()< /code> 或
Count()
,否则它们也需要包含在GROUP BY
子句中。由于您使用的是
SELECT *
,因此这相当于列出SELECT
中的所有列。因此,要么将它们全部列在
GROUP BY
中,尽可能对其余部分使用聚合函数,或者仅选择CategoryID
。If you're using
GROUP BY
in a query, all items in yourSELECT
statement must either be contained as part of an aggregate function, e.g.Sum()
orCount()
, else they will also need to be included in theGROUP BY
clause.Because you are using
SELECT *
, this is equivalent to listing ALL columns in yourSELECT
.Therefore, either list them all in the
GROUP BY
too, use aggregating functions for the rest where possible, or only select theCategoryID
.