MySQL select count by value?

MySQLMySQLi Database

You can use COUNT() function for this. Let us first create a demo table

mysql> create table countValueDemo
   -> (
   -> ShippingDatetime datetime,
   -> FirstValue int,
   -> SecondValue int
   -> );
Query OK, 0 rows affected (1.35 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into countValueDemo values('2019-01-23',1,2);
Query OK, 1 row affected (0.24 sec)
mysql> insert into countValueDemo values('2017-02-21',NULL,2);
Query OK, 1 row affected (0.13 sec)
mysql> insert into countValueDemo values('2016-04-12',1,NULL);
Query OK, 1 row affected (0.19 sec)

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

mysql> select *from countValueDemo;

The following is the output

+---------------------+------------+-------------+
| ShippingDatetime    | FirstValue | SecondValue |
+---------------------+------------+-------------+
| 2019-01-23 00:00:00 |          1 |           2 |
| 2017-02-21 00:00:00 |       NULL |           2 |
| 2016-04-12 00:00:00 |          1 |        NULL |
+---------------------+------------+-------------+
3 rows in set (0.00 sec)

Here is the query to select count by value

mysql> SELECT ShippingDatetime,
   -> COUNT(*),
   -> COUNT( IF( FirstValue = 1, 1, NULL ) ),
   -> COUNT( IF( SecondValue = 2, 1, NULL ) )
   -> FROM countValueDemo;

The following is the output

+---------------------+----------+----------------------------------------+-----------------------------------------+
| ShippingDatetime    | COUNT(*) | COUNT( IF( FirstValue = 1, 1, NULL ) ) | COUNT( IF( SecondValue = 2, 1, NULL ) ) |
+---------------------+----------+----------------------------------------+-----------------------------------------+
| 2019-01-23 00:00:00 |        3 |                                      2 |                                       2 |
+---------------------+----------+----------------------------------------+-----------------------------------------+
1 row in set (0.08 sec)
raja
Published on 01-Apr-2019 09:05:52
Advertisements