group by usage attention

 

Excerpt: When I tried to implement a SQL statement with SQL Server today, I reported the error as shown in the title. By searching in Baidu and implementing it myself, I finally found the problem and now record it.

    The statement is as follows:

    select [OrderID],[ProductID], min(UnitPrice) as MinUnitPrice 
    into NewDetails FROM [Northwind].[dbo].[Order Details] 
    Group by [OrderID]

    After executing this statement, SQL Server reports the following error:

    "Msg 8120, Level 16, State 1, Row 1 
    The column 'Northwind.dbo.Order Details.ProductID' in the select list is invalid because the column is not included in an aggregate function or GROUP BY clause."

    Baidu later found a solution in this log http://blog.sina.com.cn/s/blog_41399b8b01000997.html .

    The correct statement should be like this:

    select [OrderID],[ProductID], min(UnitPrice) as MinUnitPrice 
    into NewDetails FROM [Northwind].[dbo].[Order Details] 
    Group by [OrderID],[ProductID]

    The reason why it should be written this way is determined by the Group By clause. Below is some knowledge about Group By found in MSDN.

    The role of the Group:

    Specifies the group into which objects returned by the query expression (Select) are to be classified.

    [ GROUP BY aliasedExpression [ ,...  n ] ] 

    parameter:

 

    aliasedExpression

 

Any valid query expression on which to perform grouping. expression can be a property or a non-aggregate expression referencing the property returned by the FROM clause. Each expression in the GROUP BY clause must evaluate to a type that is comparable for equality. These types are usually scalar primitive types such as numbers, strings, and dates. Cannot be grouped by collection. Remark:

    If aggregate functions are included in the SELECT clause <select list>, then GROUP BY will calculate aggregated values ​​for each group. When GROUP BY is specified, each attribute name within any non-aggregate expression in the select list should be included in the GROUP BY list, or the GROUP BY expression must exactly match the select list expression.

    When using the Group By clause, be sure to keep the following rules in mind:

    (1) A column of non-scalar primitive type cannot be Group By, such as a column of type Group By text, image or bit cannot be used;

    (2) Each column specified by Select should appear in the Group By clause unless an aggregate function is used for this column;

    (3) Cannot Group By columns that do not exist in the table;

    (4) You can use the Where clause to eliminate rows that do not meet the conditions before grouping;

    (5) The groups returned by the Group By clause have no specific order, and the Order By clause can be used to specify the order.

    For other aspects, you can refer to the article linked above.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324927499&siteId=291194637