How can we use group functions with non-group fields in MySQL SELECT query?


We have to use GROUP BY clause if we want to use group functions with non-group fields in the SELECT query. The general syntax can be as follows

Syntax

SELECT group_function1,…, non-group-column1,… from table_name GROUP BY column_name;

Example

mysql> Select COUNT(*), id from Student GROUP BY id;
+----------+------+
| COUNT(*) | id   |
+----------+------+
| 1        | 1    |
| 1        | 2    |
| 1        | 15   |
| 1        | 17   |
| 1        | 20   |
+----------+------+
5 rows in set (0.00 sec)

mysql> Select COUNT(*), address from Student GROUP BY id;
+----------+---------+
| COUNT(*) | address |
+----------+---------+
| 1        | Delhi   |
| 1        | Mumbai  |
| 1        | Delhi   |
| 1        | Shimla  |
| 1        | Jaipur  |
+----------+---------+
5 rows in set (0.00 sec)

The field after GROUP BY clause can be different from non-group field given in SELECT query.

Swarali Sree
Swarali Sree

I love thought experiments.

Updated on: 20-Jun-2020

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements