RPAD函数及LPAD函数介绍

前言

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值