How to count horizontal values on a MySQL database?

MySQLMySQLi Database

You can use aggregate function COUNT() from MySQL to count horizontal values on a database. Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstValue int,
   SecondValue int,
   ThirdValue int,
   FourthValue int
);
Query OK, 0 rows affected (0.59 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue,FourthValue) values(-18,45,0,155);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue,FourthValue) values(0,235,null,15);
Query OK, 1 row affected (0.20 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+------------+-------------+------------+-------------+
| Id | FirstValue | SecondValue | ThirdValue | FourthValue |
+----+------------+-------------+------------+-------------+
| 1  | -18        | 45          | 0          | 155         |
| 2  | 0          | 235         | NULL       | 15          |
+----+------------+-------------+------------+-------------+
2 rows in set (0.00 sec)

Here is the query to count horizontal values on a database −

mysql> SELECT
   COUNT(FirstValue > 0 OR NULL) +
   COUNT(SecondValue > 0 OR NULL) +
   COUNT(ThirdValue > 0 OR NULL) +
   COUNT(FourthValue > 0 OR NULL) AS TOTAL_VALUE
FROM DemoTable;

This will produce the following output −

+-------------+
| TOTAL_VALUE |
+-------------+
| 4           |
+-------------+
1 row in set (0.00 sec)
raja
Published on 29-Apr-2019 14:17:24
Advertisements