Use group by to group rows [SQL Server]

Source: Internet
Author: User

The group by clause is used to group the result set and summarize and calculate each group of data.

Syntax format:

Group by [column name] [having condition expression]

Group by groups the columns specified by the "column name", groups the records with the same column values, and summarizes and calculates each group. Each group generates a record. If a "having condition expression" exists, the generated group is filtered.

 

Suppose,TablexTable includes:

--------------------------------

Columna columnb columnc


1 ABC 5

1 def 4

1 Ghi 9

2 jkl 8

2 MnO 3


IfColumnAIs a composite column, the result set will eventually have two rows, one of which summarizes the information with a value of 1, and the other of which summarizes the information with a value of 2.

IfColumnAYescomposite column, to referenceColumnBOrColumnC, The two columns must beColumnAReturns the parameters in the aggregate function of a single value. The selection list can contain (Columnb), Sum (Columnc) Or AVG (Columnc:

 SELECT ColumnA,  
MAX(ColumnB) AS MaxB,
SUM(ColumnC) AS SumC
FROM TableX
GROUP BY ColumnA

This selection statement returns two rowsColumnAEach unique value in returns one row:

ColumnA     MaxB     SumC        
----------- ---- ----------- 
1                ghi           18          
2                mno          11          
(2 row(s) affected)

However, the selection list cannot only containColumnBExpression:

 SELECT  
ColumnA,
ColumnB,
SUM(ColumnC) AS SumC
FROM TableX
GROUP BY ColumnA

Because group by can only return one rowColumnAThe value in is 1, so it cannot be returnedColumnAValue 1 inColumnBThe three values (ABC, def, and GHI) in ).

CannotNtext,Text,ImageOrBitColumns use group by or having unless the values returned by their functions belong to other data types. Such functions include substring and cast.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.