2015. 6. 20. 22:05

http://www.w3schools.com/sql/sql_groupby.asp


 Aggregate functions often need an added GROUP BY statement.


The GROUP BY Statement

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

SQL GROUP BY Syntax

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
102489051996-07-043
102498161996-07-051
102503441996-07-082

And a selection from the "Shippers" table:

ShipperIDShipperNamePhone
1Speedy Express(503) 555-9831
2United Package(503) 555-3199
3Federal Shipping(503) 555-9931

And a selection from the "Employees" table:

EmployeeIDLastNameFirstNameBirthDatePhotoNotes
1DavolioNancy1968-12-08EmpID1.picEducation includes a BA....
2FullerAndrew1952-02-19EmpID2.picAndrew received his BTS....
3LeverlingJanet1963-08-30EmpID3.picJanet has a BS degree....

SQL GROUP BY Example

Now we want to find the number of orders sent by each shipper.

The following SQL statement counts as orders grouped by shippers:

Example

SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName;

Try it yourself »

GROUP BY More Than One Column

We can also use the GROUP BY statement on more than one column, like this:

Example

SELECT Shippers.ShipperName, Employees.LastName,
COUNT(Orders.OrderID) AS NumberOfOrders
FROM ((Orders
INNER JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID)
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY ShipperName,LastName;

Try it yourself »


'SQL' 카테고리의 다른 글

The UCASE() Function  (0) 2015.06.20
HAVING Clause  (0) 2015.06.20
SUM() Function  (0) 2015.06.20
MIN() Function  (0) 2015.06.20
MAX() Function  (0) 2015.06.20
Posted by Name_null