在postgreSQL中向左边填充零

时间:2014-10-15 09:50:10

标签: sql postgresql zero-padding

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

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

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

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

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

3 个答案:

答案 0 :(得分:130)

您可以使用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

答案 1 :(得分:50)

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

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

fm前缀("填充模式")避免了生成的varchar中的前导空格。 000只是定义了您想拥有的位数。

psql (9.3.5)
Type "help" for help.

postgres=> with sample_numbers (nr) as (
postgres(>     values (1),(11),(100)
postgres(> )
postgres-> select to_char(nr, 'fm000')
postgres-> from sample_numbers;
 to_char
---------
 001
 011
 100
(3 rows)

postgres=>

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

答案 2 :(得分:11)

一样简单

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

参考文献:

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