GROUP BY statement
GROUP BY statement is used in conjunction with aggregate functions, grouping result set according to 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
SQL GROUP BY Examples
We have the following "Orders" table:
O_Id | OrderDate | OrderPrice | Customer |
---|---|---|---|
1 | 2008/12/29 | 1000 | Bush |
2 | 2008/11/23 | 1600 | Carter |
3 | 2008/10/05 | 700 | Bush |
4 | 2008/09/28 | 300 | Bush |
5 | 2008/08/06 | 2000 | Adams |
6 | 2008/07/21 | 100 | Carter |
Now, we want to find the total amount per customer (total order).
We want to use the GROUP BY statement to customers combined.
We use the following SQL statement:
SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer
The result set will look like this:
Customer | SUM(OrderPrice) |
---|---|
Bush | 2000 |
Carter | 1700 |
Adams | 2000 |
Great bar, right?
Let's look at what happens if you omit GROUP BY occur:
SELECT Customer,SUM(OrderPrice) FROM Orders
The result set will look like this:
Customer | SUM(OrderPrice) |
---|---|
Bush | 5700 |
Carter | 5700 |
Bush | 5700 |
Bush | 5700 |
Adams | 5700 |
Carter | 5700 |
The above result set is not what we need.
So why not use this SELECT statement above it? Explained as follows: The above SELECT statement specifies two (Customer and SUM (OrderPrice)). "SUM (OrderPrice)" returns a single value ( "OrderPrice" column total), the "Customer" return value 6 (each corresponding "Orders" in each row in the table). Therefore, we can not get the correct result. However, you have seen, GROUP BY statement solves this problem.
More than one GROUP BY column
We can also apply for more than one column GROUP BY statement, like this:
SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders GROUP BY Customer,OrderDate
原文链接:http://www.sysoft.net.cn/Article.aspx?ID=3737