SQL 计算列中的位数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25007223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting the number of digits in column
提问by user2343837
Here is my code
这是我的代码
select len(cast(code as float)),code
from tbl1
where code is not null
and this is the output:
这是输出:
I want a count of digits in the code column. I don't understand why the last one is counted as 12 and not 8?
我想要代码列中的数字计数。我不明白为什么最后一个被算作 12 而不是 8?
回答by Gordon Linoff
Cast it as an int
instead:
将其转换为int
:
select len(cast(code as int)), code
from tbl1
where code is not null;
Presumably, some sort of decimal values are getting counted.
据推测,某种十进制值正在被计算在内。
回答by Glen
Get the number's power of 10 and add 1. This works either if ints or reals to count the number of digits of the whole number part (note using LOG10 only works on positive numbers so I have applied ABS to get around this issue, may not be required for your data):
获取数字的 10 的幂并加 1。如果整数或实数计算整数部分的位数(注意使用 LOG10 仅适用于正数,所以我已经应用 ABS 来解决这个问题,可能不会)需要您的数据):
SELECT code, CASE WHEN Number = 0 THEN 1
ELSE FLOOR(LOG10(ABS(code))) + 1 AS NDigits
FROM tbl1