有没有办法计算 MySQL 中一列中的所有尾随零?

Is there a way to count all the trailing zeros in a column in MySQL?

我想知道是否有一种方法可以计算列中尾随零的数量。该列最多由 13 个数字组成,如下所示,我想计算实际数字之前的所有零,但不确定如何去做。

Example numbers
2200040000000 -- this would have the value 7
1411258181000 -- this would have the value 3

我已经在 Excel 中做到了这一点,但我试图在查询中直接在 MySQL 中做到这一点,而不是在 Excel 中导入数据然后编写查询因为还有更多步骤需要完成。

公式如下:

=6+RIGHT(TEXT(B17,"0.##############E+00"),2)-LEN(TEXT(B17,"0.##############E+00"))

如果有人可以建议我如何解决这个问题,我将不胜感激,因为这将真正帮助我前进,而不是与 Excel 来回走动。

您可以使用 string function TRIM(),它在 MySQL 初期就可用:

char_length(num) - char_length(trim(trailing '0' from num))

trim(...) 从字符串中删除尾随 0;原始值和修剪值之间的长度差异为您提供了字符串中尾随 0 的数量。

Demo on DB Fiddle:

create table t (num bigint);
insert into t values (2200040000000), (1411258181000);

select 
    num,
    char_length(num) - char_length(trim(trailing '0' from num)) cnt_trailing_0s
from t;
          num | cnt_trailing_0s
------------: | --------------:
2200040000000 |               7
1411258181000 |               3

你可以像这样用 reverse() 来做:

select col, 
  length(col) - length(reverse(col) + 0) trailing_zeros
from tablename

col 替换为列的实际名称。
如果存在列仅包含零的情况,则使用此:

length(col) - length(reverse(col) + 0)  + (col = 0) 

参见demo
结果:

| col           | trailing_zeros |
| ------------- | -------------- |
| 2200040000000 | 7              |
| 1411258181000 | 3              |