前言
RPAD 是 SQL 中的核心字符串操作函数,用于在字符串右侧添加填充字符直到达到指定长度。同理LPAD函数用于在字符串左侧添加填充字符直到达到指定长度;
RPAD函数定义与语法
RPAD(string, length [, pad_string])
string:原始输入字符串
length:结果字符串的总长度(整数)
pad_string:用于填充的字符或字符串
注意:只在字符串右侧添加字符,当目标长度小于原始长度时自动截断,任何参数为 NULL 返回 NULL,未指定填充字符时默认使用空格
示例
SELECT RPAD('12345', 16, '0') AS account; -- 结果: '1234500000000000'
SELECT LPAD('123', 8, '0') AS result; -- 结果: '00000123'
SELECT LPAD('Database', 5, '*'); -- 结果: 'abase'(保留最右侧5个字符)
实战
有这样一个需求,需要统计用户,近30天的活跃情况
with temp_1 as (
select
'01' as id, repeat('0',29) as act_status_bit
union all
select
'02' as id, repeat('0',29) as act_status_bit
),temp_2 as (
select
'01' as id,'1' as is_act
union all
select
'03' as id ,'1' as is_act
)
select
coalesce(t1.id,t2.id) as id
,case when t1.id is not null then substr(concat(act_status_bit,nvl(is_act,'0')),-30)
when t2.id is not null then lpad(is_act,30,'0')
end as act_status_bit
from temp_1 t1
full join temp_2 t2
on t1.id =t2.id
;
结果如下:
结果如下
id act_status_bit
01 000000000000000000000000000001
02 000000000000000000000000000000
03 000000000000000000000000000001
1万+

被折叠的 条评论
为什么被折叠?



