Aggregate functions often
need an added 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 |
SQL GROUP BY Example
Id
|
OrderDate
|
OrderPrice
|
Customer
|
1
|
2008/11/12
|
1000
|
Navis
|
2
|
2008/10/23
|
1600
|
Nilsen
|
3
|
2008/09/02
|
700
|
Navis
|
4
|
2008/09/03
|
300
|
Navis
|
5
|
2008/08/30
|
2000
|
Jensen
|
6
|
2008/10/04
|
100
|
Nilsen
|
Now we want to find the total sum (total order) of each customer.
We will have to use the GROUP BY statement to group the customers.
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)
|
Navis
|
2000
|
Nilsen
|
1700
|
Jensen
|
2000
|
GROUP BY More Than One Column
We can also use the GROUP BY statement on more than one column,
like this:
SELECT
Customer,OrderDate,SUM(OrderPrice) FROM Orders
GROUP BY Customer,OrderDate |
0 comments:
Post a Comment