Add a column count in a MySQL query on the basis of last name records?


Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(100),
   LastName varchar(100)
);
Query OK, 0 rows affected (1.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName,LastName) values('David','Miller');
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable(FirstName,LastName) values('Carol','Miller');
Query OK, 1 row affected (0.37 sec)
mysql> insert into DemoTable(FirstName,LastName) values('John','Doe');
Query OK, 1 row affected (0.21 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+----------+
| Id | FirstName | LastName |
+----+-----------+----------+
|  1 | David     | Miller   |
|  2 | Carol     | Miller   |
|  3 | John      | Doe      |
+----+-----------+----------+
3 rows in set (0.00 sec)

Following is the query to add a column count for last name records like “Miller” is appearing 2 times::

mysql> select Id, FirstName, LastName,Count from DemoTable tbl1
   JOIN (select count(*) as Count, LastName from DemoTable GROUP BY LastName) tbl2
   using(LastName);

This will produce the following output −

+----+-----------+----------+-------+
| Id | FirstName | LastName | Count |
+----+-----------+----------+-------+
|  1 | David     | Miller   |     2 |
|  2 | Carol     | Miller   |     2 |
|  3 | John      | Doe      |     1 |
+----+-----------+----------+-------+
3 rows in set (0.00 sec)

Updated on: 30-Sep-2019

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements