136

我对 PostgreSQL 比较陌生,我知道如何在 SQL Server 的左边用零填充一个数字,但我很难在 PostgreSQL 中解决这个问题。

我有一个数字列,其中最大位数为 3,最小位数为 1:如果是一位数,则左侧有两个零,如果是两位数,则为 1,例如 001、058、123。

在 SQL Server 中,我可以使用以下内容:

RIGHT('000' + cast([Column1] as varchar(3)), 3) as [Column2]

这在 PostgreSQL 中不存在。任何帮助,将不胜感激。

4

4 回答 4

238

您可以使用rpadlpad函数分别将数字填充到右侧或左侧。请注意,这不适用于数字,因此您必须使用::char::text强制转换它们:

SELECT RPAD(numcol::text, 3, '0'), -- Zero-pads to the right up to the length of 3
       LPAD(numcol::text, 3, '0')  -- Zero-pads to the left up to the length of 3
FROM   my_table
于 2014-10-15T09:55:17.527 回答
74

to_char()功能用于格式化数字:

select to_char(column_1, 'fm000') as column_2
from some_table;

前缀( “fm填充模式”)避免了生成的 varchar 中的前导空格。简单地定义了您想要的000位数。

psql (9.3.5)
键入“帮助”以获得帮助。

postgres=> with sample_numbers (nr) as (
postgres(> 值 (1),(11),(100)
postgres(>)
postgres-> 选择 to_char(nr, 'fm000')
postgres-> 来自 sample_numbers;
 to_char
---------
 001
 011
 100
(3 行)

postgres=>

有关格式图片的更多详细信息,请参阅手册:
http ://www.postgresql.org/docs/current/static/functions-formatting.html

于 2014-10-15T10:10:32.230 回答
18

一样容易

SELECT lpad(42::text, 4, '0')

参考:

sqlfiddle:http ://sqlfiddle.com/#!15/d41d8/3665

于 2014-10-15T09:54:31.493 回答
0

最简单的方法:

ltrim(to_char(Column1, '000'))
于 2021-12-14T10:42:22.270 回答