Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MySQL GROUP BY Statement

MySQL GROUP BY Statement

The GROUP BY statement groups the result set by one or more columns.

On the grouped columns we can use functions such as COUNT, SUM, AVG, and so on.

The GROUP BY statement is an important tool in SQL queries for summarizing and analyzing data; especially when dealing with large amounts of data, it can provide useful summary information.

GROUP BY Syntax



SELECT column1, aggregate_function(column2)

FROM table_name

WHERE condition

GROUP BY column1;

Suppose there is a table named orders with the following columns:order_id, customer_id, order_date, and order_amount。

We want to group by customer_id and calculate the total order amount for each customer. The SQL statement is as follows:

Example

SELECT

customer_id

,

SUM

(

order_amount

)

AS

total_amount

FROM

orders

GROUP

BY

customer_id;

In the example above, we use GROUP BY customer_id to group the results by the customer_id column, and then use SUM(order_amount) to calculate the total of the order_amount column in each group.

AS total_amount gives an alias to the calculation result, making the query result easier to read.

Notes:

Example

SELECT

column1

,

column2

,

aggregate_function

(

column3

)

FROM

TABLE_NAME

WHERE

condition

GROUP

BY

column1

,

column2;


Example Demonstration

The examples in this chapter use the following table structure and data; before use, we can import the following data into the database first.

Example

SET

NAMES utf8;

SET

FOREIGN_KEY_CHECKS

=

0

;


--  Table structure for employee_tbl


DROP

TABLE

IF

EXISTS

employee_tbl

;

CREATE

TABLE

employee_tbl

(

 

id

INT

(

11

)

NOT

NULL

,

 

name

CHAR

(

10

)

NOT

NULL

DEFAULT

''

,

 

date

datetime

NOT

NULL

,

 

signin

tinyint

(

4

)

NOT

NULL

DEFAULT

'0'

COMMENT

'Login Count'

,

 

PRIMARY

KEY

(

id

)

)

ENGINE

=

InnoDB

DEFAULT

CHARSET

=

utf8;


--  Records of employee_tbl


BEGIN

;

INSERT

INTO

employee_tbl

VALUES

(

'1'

,

'Xiao Ming'

,

'2016-04-22 15:25:33'

,

'1'

)

,

(

'2'

,

'Xiao Wang'

,

'2016-04-20 15:25:47'

,

'3'

)

,

(

'3'

,

'Xiao Li'

,

'2016-04-19 15:26:02'

,

'2'

)

,

(

'4'

,

'Xiao Wang'

,

'2016-04-07 15:26:14'

,

'4'

)

,

(

'5'

,

'Xiao Ming'

,

'2016-04-11 15:26:40'

,

'4'

)

,

(

'6'

,

'Xiao Ming'

,

'2016-04-04 15:26:54'

,

'2'

)

;

COMMIT;

SET

FOREIGN_KEY_CHECKS

=

1

;

After a successful import, execute the following SQL statement:



mysql> set names utf8;

mysql> SELECT * FROM employee_tbl;

+----+--------+---------------------+--------+

| id | name   | date                | signin |

+----+--------+---------------------+--------+

|  1 | 小明 | 2016-04-22 15:25:33 |      1 |

|  2 | 小王 | 2016-04-20 15:25:47 |      3 |

|  3 | 小丽 | 2016-04-19 15:26:02 |      2 |

|  4 | 小王 | 2016-04-07 15:26:14 |      4 |

|  5 | 小明 | 2016-04-11 15:26:40 |      4 |

|  6 | 小明 | 2016-04-04 15:26:54 |      2 |

+----+--------+---------------------+--------+

6 rows in set (0.00 sec)

Next we use the GROUP BY statement to group the data table by name and count how many records each person has:



mysql> SELECT name, COUNT(*) FROM   employee_tbl GROUP BY name;

+--------+----------+

| name   | COUNT(*) |

+--------+----------+

| 小丽 |        1 |

| 小明 |        3 |

| 小王 |        2 |

+--------+----------+

3 rows in set (0.01 sec)

Using WITH ROLLUP

WITH ROLLUP can perform the same statistics (SUM, AVG, COUNT...) on the basis of the grouped statistical data.

For example, we group the above data table by name, and then count the number of logins for each person:



mysql> SELECT name, SUM(signin) as signin_count FROM  employee_tbl GROUP BY name WITH ROLLUP;

+--------+--------------+

| name   | signin_count |

+--------+--------------+

| 小丽 |            2 |

| 小明 |            7 |

| 小王 |            7 |

| NULL   |           16 |

+--------+--------------+

4 rows in set (0.00 sec)

The record with NULL represents the login count for all people.

We can use coalesce to set a name that can replace NULL; the coalesce syntax is:



select coalesce(a,b,c);

Parameter description: if a==null, then choose b; if b==null, then choose c; if a!=null, then choose a; if a, b, and c are all null, then null is returned (meaningless).

In the following example, if the name is empty, we use the total instead:



mysql> SELECT coalesce(name, '总数'), SUM(signin) as signin_count FROM  employee_tbl GROUP BY name WITH ROLLUP;

+--------------------------+--------------+

| coalesce(name, '总数') | signin_count |

+--------------------------+--------------+

| 小丽                   |            2 |

| 小明                   |            7 |

| 小王                   |            7 |

| 总数                   |           16 |

+--------------------------+--------------+

4 rows in set (0.01 sec)