我有一张名为nums
的表。
CREATE TABLE nums (num numeric);
INSERT INTO nums SELECT * FROM (VALUES(10.11),(11.122),(12.22),(13.555)) t;
它有以下行
select * from nums
num
--------
10.11
11.122
12.22
13.555
所以我的问题是如何获得小数点后只有两位数的值(.
)?
预期产出: -
num
--------
10.11
12.22
答案 0 :(得分:2)
您可以尝试Pattern Matching
SELECT * FROM nums WHERE num::text ~ '(^\d+(\.\d{1,2})?$)';
或Mathematical Functions and Operators - Floor
SELECT * FROM nums WHERE FLOOR (num*100)=num*100
答案 1 :(得分:1)
SELECT * FROM nums WHERE left(right(num::text, 3), 1) = '.';
SELECT * FROM nums WHERE length(split_part(num::text, '.', 2)) = 2;
或者将数字modulo 1
转换为text
:
SELECT * FROM nums WHERE length((num%1)::text) = 4
最后一个独立于用于逗号的字符。
除此之外:您可以简化INSERT语句:
INSERT INTO nums VALUES(10.11),(11.122),(12.22),(13.555);
<强> SQL Fiddle. 强>
我使用100k数字的临时表进行了快速测试:
SELECT * FROM nums WHERE ...
left(right(num::text, 3), 1) = '.'; -- Total runtime: 136 ms
length(split_part(num::text, '.', 2)) = 2; -- Total runtime: 162 ms
length((num%1)::text) = 4; -- Total runtime: 179 ms
num::text ~ '(^\d+(\.\d{1,2})?$)'; -- Total runtime: 280 ms (incorrect!)
FLOOR (num*100)=num*100; -- Total runtime: 203 ms (incorrect!)
最后两个(由@varchar提供)实际上是不正确的。看评论和小提琴。