MySQL- GROUP and COUNT by date?



You can use GROUP BY clause and COUNT() function for this. The syntax is as follows −

SELECT yourColumnName1,yourColumnName2,..N,COUNT(*) as anyAliasName FROM yourTableName GROUP BY yourColumnName1,yourColumnName2;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table GroupAndCountByDate    -> (    -> Id int NOT NULL AUTO_INCREMENT,    -> TripDate date,    -> ShopId int,    -> PRIMARY KEY(Id)    -> ); Query OK, 0 rows affected (0.79 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-01-31',10); Query OK, 1 row affected (0.52 sec) mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-02-01',15); Query OK, 1 row affected (0.17 sec) mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-01-31',10); Query OK, 1 row affected (0.23 sec) mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-02-01',15); Query OK, 1 row affected (0.31 sec) mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-03-23',20); Query OK, 1 row affected (0.15 sec) mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-04-21',25); Query OK, 1 row affected (0.20 sec) mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-03-13',20); Query OK, 1 row affected (0.16 sec) mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-04-06',25); Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from GroupAndCountByDate;

The following is the output −

+----+------------+--------+ | Id | TripDate   | ShopId | +----+------------+--------+ |  1 | 2019-01-31 |     10 | |  2 | 2019-02-01 |     15 | |  3 | 2019-01-31 |     10 | |  4 | 2019-02-01 |     15 | |  5 | 2019-03-23 |     20 | |  6 | 2019-04-21 |     25 | |  7 | 2019-03-13 |     20 | |  8 | 2019-04-06 |     25 | +----+------------+--------+ 8 rows in set (0.00 sec)

Here is the query to GROUP and count by date −

mysql> select TripDate,ShopId,COUNT(*) as TOTALTRIP    -> from GroupAndCountByDate    -> group by TripDate,ShopId;

The following is the output −

+------------+--------+-----------+ | TripDate   | ShopId | TOTALTRIP | +------------+--------+-----------+ | 2019-01-31 |      10 |        2 | | 2019-02-01 |      15 |        2 | | 2019-03-23 |      20 |        1 | | 2019-04-21 |      25 |        1 | | 2019-03-13 |      20 | 1 | | 2019-04-06 | 25 | 1 | +------------+--------+-----------+ 6 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:24+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements