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
您可以使用rpad和lpad功能分别向右或向左填充数字.请注意,这不会直接对数字起作用,因此您必须使用::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)
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
zer*_*kms 12
一样容易
SELECT lpad(42::text, 4, '0')
Run Code Online (Sandbox Code Playgroud)
参考文献:
sqlfiddle:http://sqlfiddle.com/#!15/d41d8/3665
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组合不需要任何变量重复。
| 归档时间: |
|
| 查看次数: |
78101 次 |
| 最近记录: |