组功能在 SQL 服务器上不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16079787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:53:16  来源:igfitidea点击:

Group function not working on SQL server

sqlsql-servergroup-by

提问by Amarpreet Kaur

I use the below query, but it shows some repeated items. So I use the groupfunction, but it does not work.

我使用下面的查询,但它显示了一些重复的项目。所以我使用该group功能,但它不起作用。

SELECT p.productId, p.productName, p.catId, p.subCatId, p.productType,
       p.modelNo, p.picUrl, p.color, p.theme, p.productPrice, p.discountedPrice,
       p.quantity, p.details, p.mainPageDisplay, p.productPageDisplay,
       s.subCatId AS Expr1,
       s.subCatName, s.catId AS Expr2,
       s.rank, s.subCatName AS Expr3
FROM (products p INNER JOIN
      subCategories s ON p.catId = s.catId)
WHERE (p.color = 'red') group By p.productName

This query is working fine, but when I add group bythen it's not working.

这个查询工作正常,但是当我添加时group by它不起作用。

回答by Cyril Gandon

You don't need a GROUP BYfor selecting distinct rows, you need DISTINCT:

您不需要 aGROUP BY来选择不同的行,您需要DISTINCT

SELECT DISTINCT p.productId, p.productName, p.catId, p.subCatId, p.productType,
       p.modelNo, p.picUrl, p.color, p.theme, p.productPrice, p.discountedPrice,
       p.quantity, p.details, p.mainPageDisplay, p.productPageDisplay,
       s.subCatId AS Expr1,
       s.subCatName, s.catId AS Expr2,
       s.rank, s.subCatName AS Expr3
FROM (products p INNER JOIN
      subCategories s ON p.catId = s.catId)
WHERE (p.color = 'red')

回答by cms_mgr

Your SELECTstatement doesn't contain any aggregate functions, so a GROUP BYstatement is not appropriate.

您的SELECT语句不包含任何聚合函数,因此GROUP BY语句不合适。

回答by Santhosh

You need to use all the columns in the SELECT clause in GROUP BY Clause or otherwise use DISTINCT keyword after SELECT Keyword.

您需要在 GROUP BY 子句中使用 SELECT 子句中的所有列,或者在 SELECT 关键字之后使用 DISTINCT 关键字。

回答by misguided

SQL GROUP BYaggregates (consolidates and calculates) column values into a single record value. GROUP BYrequires a list of table columns on which to run the calculations.

SQL GROUP BY将列值聚合(合并和计算)到单个记录值中。GROUP BY需要运行计算的表列列表。

This linkhas an example to facilitate your understanding of the concept .

这个链接有一个例子来帮助你理解这个概念。