
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Group By and Count in a Single MySQL Query
Let us first create a table −
mysql> create table DemoTable -> ( -> ClientId int, -> Value int -> ); Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10,678); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(20,678); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(30,678); Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+-------+ | ClientId | Value | +----------+-------+ | 10 | 678 | | 20 | 678 | | 30 | 678 | +----------+-------+ 3 rows in set (0.00 sec)
Here is the query to GROUP does not work if COUNT is used −
mysql> select count(tbl.ClientId),max(tbl.ClientId) from DemoTable tbl -> group by Value;
This will produce the following output −
+---------------------+-------------------+ | count(tbl.ClientId) | max(tbl.ClientId) | +---------------------+-------------------+ | 3 | 30 | +---------------------+-------------------+ 1 row in set (0.00 sec)
Advertisements