在PostgreSQL中向左填充零 [英] Padding zeros to the left in postgreSQL

查看:522
本文介绍了在PostgreSQL中向左填充零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对PostgreSQL来说还比较陌生,我知道如何在SQL Server中用零填充数字,但是我很难在PostgreSQL中弄清楚。

I am relatively new to PostgreSQL and I know how to pad a number with zeros to the left in SQL Server but I'm struggling to figure this out in PostgreSQL.

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

I have a number column where the maximum number of digits is 3 and the min is 1: if it's one digit it has two zeros to the left, and if it's 2 digits it has 1, e.g. 001, 058, 123.

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

In SQL Server I can use the following:

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

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

This does not exist in PostgreSQL. Any help would be appreciated.

推荐答案

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

You can use the rpad and lpad functions to pad numbers to the right or to the left, respectively. Note that this does not work directly on numbers, so you'll have to use ::char or ::text to cast them:

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中向左填充零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆