在PostgreSQL中向左填充零

我对PostgreSQL相对较新,并且我知道如何在SQL Server中用左数零填充数字,但是我在PostgreSQL中努力解决这个问题。

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

在SQL Server中,我可以使用以下命令:

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

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

回答:

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

以上是 在PostgreSQL中向左填充零 的全部内容, 来源链接: utcz.com/qa/397443.html

回到顶部