GROUP BY statement in mysql
The GROUP BY statement is used in combined with the aggregate functions to group the result-set by one or more columns.
Aggregate functions:-aggregate functions are function whose return a single result.Such As MAX(),MIN().AVG(),SUM() and etc
MySQL GROUP BY Syntax
| SELECT column_name, aggregate_function(column_name) FROM table_name WHERE condition GROUP BY column_name |
MySQL GROUP BY Example
We have the following "tbl_order" table:
| Id | OrderDate | Price | Customer |
|---|---|---|---|
| 1 | 2008/11/12 | 1000 | Vikram |
| 2 | 2008/10/23 | 1600 | Mohan |
| 3 | 2008/09/02 | 700 | Vikram |
| 4 | 2008/09/03 | 300 | Vikram |
| 5 | 2008/08/30 | 2000 | Rajeev |
| 6 | 2008/10/04 | 100 | Mohan |
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(Price) FROM tbl_order GROUP BY Customer |
The result of following query will look like this:
| Customer | SUM(Price) |
|---|---|
| Vikram | 2000 |
| Mohan | 1700 |
| Rajeev | 2000 |
Comments
Post a Comment