GROUP BY clause in SQL Server
The GROUP BY clause in SQL Server (Transact-SQL) is used in the SELECT statement to retrieve data from multiple records and result groups into 1 or more columns.
The GROUP BY clause in SQL Server (Transact-SQL) is used in the SELECT statement to retrieve data from multiple records and result groups into 1 or more columns.
GROUP BY clause clause in SQL Server
SELECT bieuthuc1, bieuthuc2, … bieuthuc_n,
ham_tong (bieuthuc)
FROM bang
[WHERE dieukien]
GROUP BYbieuthuc1, bieuthuc2, . bieuthuc_n;
Variable name or variable value
bieuthuc1, bieuthuc2, . bieuthuc_n
The expression is not within the total function and must be in the GROUP BY clause.
ham_tong
Can be functions like SUM, COUNT, MIN, MAX or AVG.
state
The table to retrieve records from, must have at least 1 table in the FROM clause.
WHERE dieukien
Option. The condition that the record must meet to be selected is in the WHERE clause.
For example - use the SUM function
SELECT ten_sanpham, SUM(soluong) AS 'Tong so luong'
FROM sanpham
GROUP BY ten_sanpham;
This example uses the SUM calculation function to return the product name and total quantity (by product name).
Because you give a column (ten_sanpham) in the SELECT statement and not in the SUM function, you must use the GROUP BY clause.
For example - use the COUNT function
SELECT relatedly_id, COUNT (*) AS 'So nhan vien'
FROM nhanvien
WHERE ho = 'Anderson'
GROUP BY quanly_id;
In this example, the COUNT function will return quanly_id and the number of employees with the last name is Anderson.
For example - use the MIN function
SELECT loai_sanpham, MIN(soluong) AS 'So luong it nhat'
FROM sanpham
GROUP BY loai_sanpham;
The GROUP BY clause used with the MIN function above will return the product type and the minimum quantity for that product type.
For example - use the MAX function
SELECT bophan, MAX(luong) AS 'Luong cao nhat'
FROM nhanvien
GROUP bophan;
This final example returns the name of each department and the maximum salary in the department.
Previous article: Conditions EXISTS in SQL Server
Lesson: HAVING clause in SQL Server
You've just finished reading the article "GROUP BY clause in SQL Server" edited by the TipsMake team. You can save group-by-clause-in-sql-server.pdf to your computer here to read later or print it out. We hope this article has provided you with many useful tech tips and tricks. You can search for similar articles on tips and guides. Thank you for reading and for following us regularly.