Sum of digits of year in MySQL?


At first, you need to extract the last digit and add the extracted value. And the same goes in till we get the sum of all digits of the year, for example, for the year 2020 −

2 + 0 + 2 + 0
= 4

The concept is as follows to extract the last digit from the year. Following is the query −

select floor(@yourVariableName % 10);

Following is the query to sum the digits of year −

mysql> set @year_column_value = 2020;
Query OK, 0 rows affected (0.00 sec)
mysql> select
−> floor(@year_column_value / 1000)
−> + floor(@year_column_value % 1000 / 100)
−> + floor(@year_column_value % 100 / 10)
−> + floor(@year_column_value % 10) AS SUM_OF_DIGITS_OF_YEAR;

This will produce the following output −

+-----------------------+
| SUM_OF_DIGITS_OF_YEAR |
+-----------------------+
|                     4 |
+-----------------------+
1 row in set (0.00 sec)

Updated on: 19-Nov-2020

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements