MySQL- GROUP和COUNT按日期?
您可以COUNT()
为此使用GROUPBY子句和函数。语法如下-
SELECT yourColumnName1,yourColumnName2,..N,COUNT(*) as anyAliasName FROM yourTableName GROUP BY yourColumnName1,yourColumnName2;
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table GroupAndCountByDate -> ( -> Id int NOT NULL AUTO_INCREMENT, -> TripDate date, -> ShopId int, -> PRIMARY KEY(Id) -> );
现在,您可以使用insert命令在表中插入一些记录。查询如下-
mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-01-31',10); mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-02-01',15); mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-01-31',10); mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-02-01',15); mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-03-23',20); mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-04-21',25); mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-03-13',20); mysql> insert into GroupAndCountByDate(TripDate,ShopId) values('2019-04-06',25);
使用select语句显示表中的所有记录。查询如下-
mysql> select *from GroupAndCountByDate;
以下是输出-
+----+------------+--------+ | 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)
这是对GROUP的查询,并按日期计数-
mysql> select TripDate,ShopId,COUNT(*) as TOTALTRIP -> from GroupAndCountByDate -> group by TripDate,ShopId;
以下是输出-
+------------+--------+-----------+ | 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)