在postgreSQL中向左边填充零

Ben*_*Ben 76 sql postgresql zero-padding

我对PostgreSQL比较新,我知道如何在SQL Server中用左边的零填充数字,但我很难在PostgreSQL中弄清楚这一点.

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

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

RIGHT('000' + cast([Column1] as varchar(3)), 3) as [Column2]
Run Code Online (Sandbox Code Playgroud)

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

Mur*_*nik 147

您可以使用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
Run Code Online (Sandbox Code Playgroud)

  • 警告:与经典的“printf”不同,如果字符串不适合,这些愚蠢的函数会默默地将其削减到合适的大小。所以你可能需要一个“case when length(foo) ...”。 (4认同)
  • @EvanCarroll它们都很有用 - 这个允许你为字符串长度指定一个数字 - 另一个需要知道'fm'代表填充模式并允许你指定一个格式图片 (3认同)
  • @EvanCarroll这是正确的答案 - 你在说什么? (2认同)

a_h*_*ame 52

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

select to_char(column_1, 'fm000') as column_2
from some_table;
Run Code Online (Sandbox Code Playgroud)

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

  • 我很好奇是否有解决方案,如果 # 如果长于 to_Char 中指定的值,则它会转换为 ###。无论如何,是否有特定的最小零个数,然后从中增长更大的数字?例如,如果您为 lpad 指定 3,数字的格式将类似于 001 010 100 .. 1001 (4认同)
  • 如果数字太长,`to_char` 会将其转换为###。哦 (3认同)

zer*_*kms 12

一样容易

SELECT lpad(42::text, 4, '0')
Run Code Online (Sandbox Code Playgroud)

参考文献:

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


Sch*_*ems 5

LPAD我对和感到沮丧TO_CHAR,因为如果你的字符串超过最小长度,它们就不起作用。我无法说出这有多高效,但您可以链接起来FORMAT给您一个最小大小的字符串,然后使用以下命令将所有空格替换为零REPLACE

with sample_numbers (nr) as (
    values (1),(11),(100),(1000)
)
SELECT REPLACE(FORMAT('%3s', nr), ' ', '0')
from sample_numbers;
 replace
---------
 001
 011
 100
 1000
(4 rows)
Run Code Online (Sandbox Code Playgroud)

与其他方法对比TO_CHAR

with sample_numbers (nr) as (
    values (1),(11),(100),(1000)
)
SELECT to_char(nr, 'fm000')
from sample_numbers;
 to_char
---------
 001
 011
 100
 ###
(4 rows)
Run Code Online (Sandbox Code Playgroud)

(注意最后一个值是###而不是1000

LPAD

with sample_numbers (nr) as (
    values (1),(11),(100),(1000)
)
SELECT LPAD(nr::varchar(255), 3, '0')
from sample_numbers;
 lpad
------
 001
 011
 100
 100
(4 rows)
Run Code Online (Sandbox Code Playgroud)

(注意最后一个值是100而不是1000

还有其他涉及使用的方法CASE,但我喜欢REPLACE&FORMAT组合不需要任何变量重复。